6

我有以下错误处理RestTemplate

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

问题:我怎样才能用 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");
    }
}

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

4

1 回答 1

2

您将使用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"));
于 2019-08-12T10:12:36.230 回答