小编Moh*_*ale的帖子

在Spring Boot中使用Web Client Mono获取API响应错误消息

我正在使用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响应?

spring web-client spring-boot spring-webflux

10
推荐指数
3
解决办法
1万
查看次数

标签 统计

spring ×1

spring-boot ×1

spring-webflux ×1

web-client ×1