在Spring WebFlux中处理全球方案

贾甘纳坦·拉贾戈帕兰

我有一个Rest Web Client来执行API调用,并且按以下方式处理异常。

我想以全局方式处理404、401和400错误,而不是在单个客户端级别进行处理。我们如何才能实现相同目标。

public Mono<ProductResponse> getProductInformation(String productId) {
        return webClient.get()
                .uri("/v1/products/"+productId)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .onStatus( httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus), clientResponse -> {
                    Mono<NotFound> notFound = clientResponse.bodyToMono(NotFound.class);
                    return notFound.flatMap( msg -> {
                        log.info(" Error Message {}" , msg.getErrorMsg());
                        return Mono.error(new NotFoundException(msg.getErrorMsg()));
                    });
                }).onStatus( httpStatus -> HttpStatus.UNAUTHORIZED.equals(httpStatus), clientResponse -> {
                    Mono<NotFound> notFound = clientResponse.bodyToMono(NotFound.class);
                   return Mono.error(new NotAuthorisedException("Unauthorised"));
                }).bodyToMono(ProductResponse.class);
    }
Abhinaba Chakraborty

两种方法:

  1. Webclient的异常都包装在WebClientResponseException类中。您可以像这样使用Spring的ExceptionHandler注释来处理
  @ExceptionHandler(WebClientResponseException.class)
  public ResponseEntity handleWebClientException(WebClientResponseException ex){
    return ResponseEntity.badRequest().body(ex.getResponseBodyAsString());
  }

注–在这里,您可以使用诸如getStatusCode()getRawStatusCode()getStatusText()getHeaders()getResponseBodyAsString()之类的方法,根据响应状态编写复杂的条件逻辑您还可以获取使用方法getRequest发送的请求的引用

  1. 在构造webclient bean时使用ExchangeFilterFunction
  @Bean
  public WebClient buildWebClient() {

    Function<ClientResponse, Mono<ClientResponse>> webclientResponseProcessor =
        clientResponse -> {
          HttpStatus responseStatus = clientResponse.statusCode();
          if (responseStatus.is4xxClientError()) {
            System.out.println("4xx error");
            return Mono.error(new MyCustomClientException());
          } else if (responseStatus.is5xxServerError()) {
            System.out.println("5xx error");
            return Mono.error(new MyCustomClientException());
          }
          return Mono.just(clientResponse);
        };

    return WebClient.builder()
        .filter(ExchangeFilterFunction.ofResponseProcessor(webclientResponseProcessor)).build();
  }

然后,您可以使用@ExceptionHandler处理MyCustomClientException或将其保持不变

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章