为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Resttemplate异常处理

Spring Resttemplate异常处理

30秒到达战场 2019-11-12 14:43:10
下面是代码片段;基本上,当错误代码不是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]我真的需要在尝试中包装其余模板交换方法吗?那么代码的目的是什么?
查看完整描述

3 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

您想要创建一个实现的类,ResponseErrorHandler然后使用它的一个实例来设置其余模板的错误处理:


public class MyErrorHandler implements ResponseErrorHandler {

  @Override

  public void handleError(ClientHttpResponse response) throws IOException {

    // your error handling here

  }


  @Override

  public boolean hasError(ClientHttpResponse response) throws IOException {

     ...

  }

}


[...]


public static void main(String args[]) {

  RestTemplate restTemplate = new RestTemplate();

  restTemplate.setErrorHandler(new MyErrorHandler());

}

此外,Spring还提供了一个类DefaultResponseErrorHandler,您可以扩展该类而不是实现接口,以防万一您只想覆盖该handleError方法。


public class MyErrorHandler extends DefaultResponseErrorHandler {

  @Override

  public void handleError(ClientHttpResponse response) throws IOException {

    // your error handling here

  }

}

查看其源代码,以了解Spring如何处理HTTP错误。


查看完整回答
反对 回复 2019-11-12
  • 3 回答
  • 0 关注
  • 3513 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信