How to catch ConnectionException in Spring WebClient?
Asked Answered
M

1

8

I have the following error handling in RestTemplate:

try {
   restTemplate.postForObject(..);
} catch (ResourceAccessException e) {
   throw new CustomException("host is down");
}

Question: how can I achieve the same with spring WebClient?

try {
   webClient.post()...block();
} catch (Exception e) {
    //cannot check due to package private access
    //if (e instanceof Exceptions.ReactiveException)
    if (e.getCause() instanceof java.net.ConnectException) {
         throw new CustomException("host is down");
    }
}

Problem: I cannot directly catch ConnectionException because it is wrapped inside the ReactiveException. Could I do better than applying multiple instanceof checks for any real underlying exceptions?

Maurizia answered 12/8, 2019 at 9:41 Comment(0)
W
3

you'd handle the error reactively, using onErrorMap with the check you're doing in the predicate (see https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#onErrorMap-java.lang.Class-java.util.function.Function-)

Note: Didn't check whether this compiles, and you can also replace the isAssignableFrom check with instanceof, if you like.

WebClient.post().....onErrorMap(t -> t.getCause.isAssignableFrom(ConnectException.class), t -> new CustomException("host is down"));
Whenas answered 12/8, 2019 at 10:12 Comment(2)
t.getCause().getClass().equals(ConnectException.class)Cari
You can just pass ConnectionException.class. There's an overload of onErrorMap that does the instanceof check for you.Thigmotropism

© 2022 - 2024 — McMap. All rights reserved.