liveBook · Manning

onStatus()

As explained in Spring in Action, Sixth Edition

onStatus() is a WebClient response-handling operation that associates HTTP status predicates with functions producing errors.

onStatus() customizes WebClient error handling by matching HTTP statuses and converting matching responses into application-specific errors. It receives a predicate for the status and a function that returns a Mono<Throwable>. section 12.4.4

Turning a missing ingredient into a domain error

A request for an ingredient can translate every 4xx response into UnknownIngredientException. A narrower predicate can target only HTTP 404. When the resulting Mono is subscribed to, successful data reaches the data consumer; a failed request reaches the error consumer. section 12.4.4

Mono<Ingredient> ingredientMono = webClient
    .get()
    .uri("http://localhost:8080/ingredients/{id}", ingredientId)
    .retrieve()
    .onStatus(HttpStatus::is4xxClientError,
            response -> Mono.just(new UnknownIngredientException()))
    .bodyToMono(Ingredient.class);

Use onStatus() after retrieve() to map client-error statuses to a custom exception before decoding the response body. section 12.4.4

Mono<Ingredient> ingredientMono = webClient
    .get()
    .uri("http://localhost:8080/ingredients/{id}", ingredientId)
    .retrieve()
    .onStatus(status -> status == HttpStatus.NOT_FOUND,
            response -> Mono.just(new UnknownIngredientException()))
    .bodyToMono(Ingredient.class);

Narrow the predicate when only HTTP 404 should produce the custom error. section 12.4.4

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains predicate and Throwable-producing function usage with 4xx and 404 examples, but does not detail exception implementation.
Examples
Uses ingredient lookup, HTTP 404, UnknownIngredientException, subscription error consumers, and broad versus narrow status predicates.
What it assumes
Assumes familiarity with WebClient retrieval, Mono subscription, HTTP statuses, and success and error consumers.
What you can do after
Apply WebClient onStatus() to translate selected HTTP responses into domain-specific reactive errors.
How it connects
Connects WebClient, retrieve(), ResponseSpec, Mono, ClientResponse, HTTP status codes, and exchangeToMono().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.