【问题标题】:Add Exception handler for Spring Web Client为 Spring Web 客户端添加异常处理程序
【发布时间】:2018-12-10 20:49:05
【问题描述】:

我将此代码用于 REST API 请求。

WebClient.Builder builder = WebClient.builder().baseUrl(gatewayUrl);
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(opt -> opt.sslContext(sslContext));
builder.clientConnector(httpConnector);

如何添加连接异常处理程序?我想实现一些自定义逻辑?这个功能容易实现吗?

【问题讨论】:

标签: spring spring-webflux


【解决方案1】:

如果我在由于 SSL 凭据而导致连接失败的情况下理解您的问题,那么您应该会在 REST 响应中看到连接异常本身。 您可以通过在WebClient.ResponseSpec#onStatus 上获得的Flux 结果处理该异常。 #onStatus 的文档说:

注册一个自定义错误函数,当给定 HttpStatus 谓词适用。函数返回的异常 将从bodyToMono(Class)bodyToFlux(Class) 返回。经过 默认情况下,错误处理程序是抛出一个 WebClientResponseException 当响应状态码为 4xx5xx

看看this example

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxServerError, response -> ...) // This is in the docs there but is wrong/fatfingered, should be is4xxClientError
            .onStatus(HttpStatus::is5xxServerError, response -> ...)
            .bodyToMono(Person.class);

对于您的问题,连接错误应该在调用后自行显现,您可以自定义它在反应管道中的传播方式:

Mono<Person> result = client.get()
            .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .onStatus(HttpStatus::is4xxClientError, response -> {
                 ... Code that looks at the response more closely...
                 return Mono.error(new MyCustomConnectionException());
             })
            .bodyToMono(Person.class);

希望对您有所帮助。

【讨论】:

  • 我们如何在此处也记录响应?连同异常?
  • @Rocky4Ever ,我认为您需要使用.exchange() 或代替.retrieve() 或实现全局错误处理程序来捕获异常并记录它们,然后再根据需要重新抛出它们。
猜你喜欢
  • 2019-07-27
  • 2015-04-26
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多