Moh*_*ale 10 spring web-client spring-boot spring-webflux
我正在使用webflux Mono(在Spring Boot 5中)使用外部API。当API响应状态代码为200时,我能够很好地获取数据,但是当API返回错误时,我无法从API检索错误消息。Spring WebClient错误处理程序始终将消息显示为
ClientResponse has erroneous status code: 500 Internal Server Error,但是当我使用PostMan时,API返回此JSON响应,其状态码为500。
{
"error": {
"statusCode": 500,
"name": "Error",
"message":"Failed to add object with ID:900 as the object exists",
"stack":"some long message"
}
}
Run Code Online (Sandbox Code Playgroud)
我使用WebClient的请求如下
webClient.getWebClient()
.post()
.uri("/api/Card")
.body(BodyInserters.fromObject(cardObject))
.retrieve()
.bodyToMono(String.class)
.doOnSuccess( args -> {
System.out.println(args.toString());
})
.doOnError( e ->{
e.printStackTrace();
System.out.println("Some Error Happend :"+e);
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,当API返回状态代码为500的错误时,如何访问JSON响应?
小智 6
如果要检索错误详细信息:
WebClient webClient = WebClient.builder()
.filter(ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
if (clientResponse.statusCode().isError()) {
return clientResponse.bodyToMono(ErrorDetails.class)
.flatMap(errorDetails -> Mono.error(new CustomClientException(clientResponse.statusCode(), errorDetails)));
}
return Mono.just(clientResponse);
}))
.build();
Run Code Online (Sandbox Code Playgroud)
与
class CustomClientException extends WebClientException {
private final HttpStatus status;
private final ErrorDetails details;
CustomClientException(HttpStatus status, ErrorDetails details) {
super(status.getReasonPhrase());
this.status = status;
this.details = details;
}
public HttpStatus getStatus() {
return status;
}
public ErrorDetails getDetails() {
return details;
}
}
Run Code Online (Sandbox Code Playgroud)
并与ErrorDetails类映射错误正文
每个请求的变体:
webClient.get()
.exchange()
.map(clientResponse -> {
if (clientResponse.statusCode().isError()) {
return clientResponse.bodyToMono(ErrorDetails.class)
.flatMap(errorDetails -> Mono.error(new CustomClientException(clientResponse.statusCode(), errorDetails)));
}
return clientResponse;
})
Run Code Online (Sandbox Code Playgroud)
看看.onErrorMap(),这给了你一个例外。由于您可能还需要查看 exchange() 的 body(),因此不要使用retrieve,但是
.exchange().flatMap((ClientResponse) response -> ....);
Run Code Online (Sandbox Code Playgroud)
就像@Frischling建议的那样,我将请求更改为如下所示
return webClient.getWebClient()
.post()
.uri("/api/Card")
.body(BodyInserters.fromObject(cardObject))
.exchange()
.flatMap(clientResponse -> {
if (clientResponse.statusCode().is5xxServerError()) {
clientResponse.body((clientHttpResponse, context) -> {
return clientHttpResponse.getBody();
});
return clientResponse.bodyToMono(String.class);
}
else
return clientResponse.bodyToMono(String.class);
});
Run Code Online (Sandbox Code Playgroud)
我还注意到,从1xx到5xx有几个状态代码,这将使我在不同情况下的错误处理更加容易
| 归档时间: |
|
| 查看次数: |
14126 次 |
| 最近记录: |