【问题标题】:How to catch ConnectionException in Spring WebClient?如何在 Spring WebClient 中捕获 ConnectionException?
【发布时间】:2019-12-18 21:29:44
【问题描述】:

我在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 检查任何真正的潜在异常做得更好吗?

【问题讨论】:

    标签: java spring spring-webflux spring-webclient


    【解决方案1】:

    您可以反应性地处理错误,将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"));
    

    【讨论】:

    • t.getCause().getClass().equals(ConnectException.class)
    • 你可以只传递 ConnectionException.class。有一个重载的 onErrorMap 会为您检查 instanceof。
    猜你喜欢
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多