Spring Rest 客户端异常处理

2024-03-17

我正在使用弹簧RestTemplate消耗休息服务(在春季休息中暴露)。我能够消费成功场景。但对于负面情况,服务会返回错误消息和错误代码。我需要在我的网页中显示这些错误消息。

例如对于无效请求,服务抛出异常HttpStatus.BAD_REQUEST有正确的消息。如果我放置 try-catch 块,它会进入 catch 块,但我无法获取ResponseEntity object.

try {
    ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
        new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
    });
    responseEntity.getStatusCode();
    } catch (Exception e) {
        //TODO How to get response here, so that i can get error messages?
        e.printStackTrace();
    }

如何获得ResponseWrapper对于例外情况?

我读到CustomRestTemplate and ResponseExtractor from here https://stackoverflow.com/questions/3322381/spring-resttemplate-behavior-when-handling-responses-with-a-status-of-no-content但无法决定哪一个最适合我的情况。


我找到了解决方案。HttpClientErrorException为我工作。

It has e.getResponseBodyAsString()返回 ResponseBody 的函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Rest 客户端异常处理 的相关文章

随机推荐