使用 Webclient 处理成功/错误响应

Handle success/error response using Webclient

提问人:Pale Dot 提问时间:11/13/2023 更新时间:11/13/2023 访问量:20

问:

我有一个api,我在Spring Boot中使用WebClient调用当api调用成功(即200状态)时,我得到的响应如下

{
  "id": 123,
  "username": "john_doe",
  "email": "[email protected]",
  "createdAt": "2023 march"
}

当 API 调用不成功(400 或 500 状态范围)时,响应为

{
    "error": "details",
    "code": "400",
    "message": "Bad Request",
    "details": "The request body is missing a required field."
}

如何处理它。我写了下面的代码。它为成功调用工作,但我无法失败状态代码。

  • UserResponse - Pojo 映射成功响应

  • ApiErrorResponse - Pojo 映射错误响应

    公共类 ResponseWrapper { 私人最终布尔成功; private final String 消息; 私有 UserResponse userResponse; 私有 ApiErrorResponse apiErrorResponse;

法典

public ResponseWrapper fetchUserData2(UserRequest userRequest) {
        UserResponse userResponse = apiWebClient.post()
                .uri("https://demo4108264.mockable.io/test")
                .body(Mono.just(userRequest), UserRequest.class)
                .retrieve()
                
                .onStatus(HttpStatus::is4xxClientError, response ->
                response.bodyToMono(ApiErrorResponse.class)
                        .flatMap(errorResponse -> Mono.error(new CustomApiException(errorResponse)))
        )
                .bodyToMono(UserResponse.class)
                .block();
        
        // Process the response based on success or error
        if (userResponse != null) {
            System.out.println(" success " + userResponse.getId());
            // Handle success
            return new ResponseWrapper(true, "API call successful", userResponse,null);
        } else {
            System.out.println(" error occured " );
            return new ResponseWrapper(false, "API call failed", null,null);
        }
spring-boot spring-webflux webclient spring-rest

评论

1赞 Toerktumlare 11/16/2023
当你调用并且响应式代码返回一个时,代码将抛出一个异常,在你的情况下,你处理该异常,就像你在控制器中处理任何 Spring 异常一样,通过使用blockMono::ErrorCustomApiExceptionControllerAdvice

答: 暂无答案