【问题标题】:Webclient Error Handling - Spring WebfluxWebclient 错误处理 - Spring Webflux
【发布时间】:2021-08-06 20:55:42
【问题描述】:

我想在以下条件下抛出我的自定义异常:

  1. 如果我得到 json 格式的正确错误响应,我想反序列化它并在 onStatus()

    中抛出名为 CommonException 的异常
  2. 如果我收到 HTML 内容作为响应的一部分,或者反序列化没有成功发生,那么我想抛出我在 onErrorMap()

    中创建的 GenericException >
  3. 在抛出 GenericException 时,我想将相同的 HttpStatus 代码传递给从下游响应中获得的上游。

     IdVerificationResponse idVerificationResponse = client.get()
     .uri(idVerificationUrl)
     .headers(headers -> headers.addAll(httpEntity.getHeaders()))
     .retrieve()
     .onStatus(HttpStatus::isError, response ->
         //Throw this one only if deserialization of error response to IdVerificationErrorResponse class happens successfully
    
         response.bodyToMono(IdVerificationErrorResponse.class)
             .flatMap(error -> Mono.error(CommonException.builder().message(error.getCustomMessage()).build()))
     )
     .bodyToMono(IdVerificationResponse.class)
     .onErrorMap(error -> {
         //Come over here only if there is an error in deserialization in onStatus()
    
         //How to get the HttpStatus we are getting as part of error response from the downstream
         HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
         ApiErrorDetails errorDetailsObj = ApiErrorDetails.builder().errorCode(httpStatus.name()).errorDescription("Error related to HTML")
               .errorDetails("Error related to HTML").build();
         ErrorDetails errorDetails = ErrorDetails.builder().errors(errorDetailsObj).build();
         return GenericException.builder().errorDetails(errorDetails).httpStatus(httpStatus).build();
     }).block();
    

目前 onErrorMap() 每次都会被调用并覆盖我在 onStatus() 中抛出的异常

【问题讨论】:

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


    【解决方案1】:

    找到解决办法

    IdVerificationResponse idVerificationResponse = client.get()
        .uri(processCheckUrl)
        .headers(headers -> headers.addAll(httpEntity.getHeaders()))
        .retrieve()
        .onStatus(HttpStatus::isError, response -> {
                HttpStatus errorCode = response.statusCode();
                return response.bodyToMono(IdVerificationErrorResponse.class)
                    .onErrorMap(error -> new Exception("Throw your generic exception over here if there is any error in deserialization"))
                    .flatMap(error -> Mono.error(new Exception("Throw your custom exception over here after successful deserialization")));
            })
        .bodyToMono(IdVerificationResponse.class).block();
    

    【讨论】:

    • 您是否仅将块用于此示例目的?如果不是,那么这将是一个不好的做法,您应该返回 Mono 而不是阻止它。
    • @PratikSherke 是的,它仅用于示例目的。
    猜你喜欢
    • 2019-12-04
    • 2018-08-18
    • 2021-08-13
    • 2018-07-05
    • 2018-05-09
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多