Spring Resttemplate异常处理

下面是代码片段;基本上,当错误代码不是200时,我正在尝试传播异常。


ResponseEntity<Object> response = restTemplate.exchange(url.toString().replace("{version}", version),

                    HttpMethod.POST, entity, Object.class);

            if(response.getStatusCode().value()!= 200){

                logger.debug("Encountered Error while Calling API");

                throw new ApplicationException();

            }

但是,如果服务器发出500响应,我将收到异常


org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error

    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94) ~[spring-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]

我真的需要在尝试中包装其余模板交换方法吗?那么代码的目的是什么?


30秒到达战场
浏览 3529回答 3
3回答

白猪掌柜的

您想要创建一个实现的类,ResponseErrorHandler然后使用它的一个实例来设置其余模板的错误处理:public class MyErrorHandler implements ResponseErrorHandler {&nbsp; @Override&nbsp; public void handleError(ClientHttpResponse response) throws IOException {&nbsp; &nbsp; // your error handling here&nbsp; }&nbsp; @Override&nbsp; public boolean hasError(ClientHttpResponse response) throws IOException {&nbsp; &nbsp; &nbsp;...&nbsp; }}[...]public static void main(String args[]) {&nbsp; RestTemplate restTemplate = new RestTemplate();&nbsp; restTemplate.setErrorHandler(new MyErrorHandler());}此外,Spring还提供了一个类DefaultResponseErrorHandler,您可以扩展该类而不是实现接口,以防万一您只想覆盖该handleError方法。public class MyErrorHandler extends DefaultResponseErrorHandler {&nbsp; @Override&nbsp; public void handleError(ClientHttpResponse response) throws IOException {&nbsp; &nbsp; // your error handling here&nbsp; }}查看其源代码,以了解Spring如何处理HTTP错误。
打开App,查看更多内容
随时随地看视频慕课网APP