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
