在Spring Boot中使用Web Client Mono获取API响应错误消息 [英] Get API response error message using Web Client Mono in Spring Boot

查看:586
本文介绍了在Spring Boot中使用Web Client Mono获取API响应错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用webflux Mono(在Spring Boot 5中)使用外部API.当API响应状态代码为200时,我能够很好地获取数据,但是当API返回错误时,我无法从API检索错误消息. Spring WebClient错误处理程序始终将消息显示为

I am using webflux Mono (in Spring boot 5) to consume an external API. I am able to get data well when the API response status code is 200, but when the API returns an error I am not able to retrieve the error message from the API. Spring webclient error handler always display the message as

ClientResponse has erroneous status code: 500 Internal Server Error,但是当我使用PostMan时,API会以状态代码500返回此JSON响应.

ClientResponse has erroneous status code: 500 Internal Server Error, but when I use PostMan the API returns this JSON response with status code 500.

{
 "error": {
    "statusCode": 500,
    "name": "Error",
    "message":"Failed to add object with ID:900 as the object exists",
    "stack":"some long message"
   }
}

我使用WebClient的请求如下

My request using WebClient is as follows

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);
            });

我的问题是,当API返回状态码为500的错误时,如何访问JSON响应?

My question is, how can I get access to the JSON response when the API returns an Error with status code of 500?

推荐答案

查看.onErrorMap(),这使您可以查看异常.由于您可能还需要查看exchange()的body(),因此请不要使用检索,而是

Look at .onErrorMap(), that gives you the exception to look at. Since you might also need the body() of the exchange() to look at, don't use retrieve, but

.exchange().flatMap((ClientResponse) response -> ....);

这篇关于在Spring Boot中使用Web Client Mono获取API响应错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆