Spring Rest客户端异常处理

Abh*_*ngh 9 java rest spring rest-client

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

例如,对于无效请求,服务会抛出HttpStatus.BAD_REQUEST适当的消息.如果我把try-catch块转到catch块而我无法得到ResponseEntity对象.

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();
    }
Run Code Online (Sandbox Code Playgroud)

如何获得ResponseWrapper例外情况?

我从这里开始阅读CustomRestTemplate,但无法确定哪一个最适合我的情况.ResponseExtractor

Abh*_*ngh 14

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

它具有e.getResponseBodyAsString()返回ResponseBody的功能.


phi*_*zel 7

您可能想要区分:

HttpClientErrorException(HTTP-Status> = 400)或HttpServerErrorException(HTTP-Status> = 500)或甚至RestClientException.

此外,还有一个关于定义自己的ErrorHandler的好文档,请参阅此链接