提问人:Pale Dot 提问时间:11/13/2023 更新时间:11/13/2023 访问量:20
使用 Webclient 处理成功/错误响应
Handle success/error response using Webclient
问:
我有一个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);
}
答: 暂无答案
评论
block
Mono::Error
CustomApiException
ControllerAdvice