如何在 Spring WebClient 中捕获 ConnectionException?

mem*_*und 6 java spring spring-webflux spring-webclient

我有以下错误处理RestTemplate

try {
   restTemplate.postForObject(..);
} catch (ResourceAccessException e) {
   throw new CustomException("host is down");
}
Run Code Online (Sandbox Code Playgroud)

问题:我怎样才能用 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:我不能直接捕捉,ConnectionException因为它被包裹在ReactiveException. 我能比instanceof对任何真正的潜在异常应用多次检查做得更好吗?

Fri*_*ing 3

onErrorMap您可以使用在谓词中进行的检查来反应性地处理错误(请参阅https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#onErrorMap-java .lang.Class-java.util.function.Function- )

注意:没有检查是否可以编译,如果你愿意,你也可以用instanceof替换isAssignableFrom检查。

WebClient.post().....onErrorMap(t -> t.getCause.isAssignableFrom(ConnectException.class), t -> new CustomException("host is down"));
Run Code Online (Sandbox Code Playgroud)

  • t.getCause().getClass().equals(ConnectException.class) (2认同)