【问题标题】:How to handle 404 in webclient retrive如何在 webclient 检索中处理 404
【发布时间】:2021-07-31 19:34:32
【问题描述】:

我是 spring webclient 的新手,我编写了一个通用方法,可用于在我的应用程序中使用 rest api:

public <T> List<T> get(URI url, Class<T> responseType) {
        return  WebClient.builder().build().get().uri(url)
                   .header("Authorization", "Basic " + principal)
                   .retrieve().bodyToFlux(responseType).collectList().block();
}

如果使用 rest-api 返回 404,我想返回并清空列表。

有人可以建议如何实现吗?

【问题讨论】:

    标签: spring-boot spring-webflux spring-webclient


    【解决方案1】:

    默认情况下,retrieve 方法会针对任何 4xx 和 5xx 错误抛出 WebClientResponseException 异常

    默认情况下,4xx 和 5xx 响应会导致 WebClientResponseException。

    你可以使用onErrorResume

     webClient.get()
     .uri(url)
     .retrieve()
     .header("Authorization", "Basic " + principal)
     .bodyToFlux(Account.class)
     .onErrorResume(WebClientResponseException.class,
          ex -> ex.getRawStatusCode() == 404 ? Flux.empty() : Mono.error(ex))
     .collectList().block();
    

    【讨论】:

      【解决方案2】:

      你也可以使用onStatus 它允许你过滤你想要的异常

      public <T> List<T> get(URI url, Class<T> responseType) {
          return  WebClient.builder().build().get().uri(url)
                  .header("Authorization", "Basic " + principal)
                  .retrieve()
                  .onStatus(HttpStatus::is4xxClientError, this::handleErrors)
                  .bodyToFlux(responseType)
                  .collectList().block();
      }
      
      private Mono<Throwable> handleErrors(ClientResponse response ){
          return response.bodyToMono(String.class).flatMap(body -> {
              log.error("LOg errror");
              return Mono.error(new Exception());
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2018-10-17
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 2021-07-14
        • 2016-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多