RestTemplate在连接失败的时候,会直接抛出异常,我们可以通过设置
restTemplate.setErrorHandler(new CustomErrorHandler());
来处理异常。但是这种灵活度不够,不能在业务发生点灵活处理。
还有一种思路就是捕获各种情况下的异常,之后根据异常类型就知道对应的异常了。
HttpClientErrorException - 在HTTP状态为4xx的情况下
HttpServerErrorException - 在HTTP状态为5xx的情况下
UnknownHttpStatusCodeException - 如果HTTP状态未知
ResourceAccessException - 请求超时,Spring将抛出该实例下的底层异常将是java.net.SocketTimeoutException。
代码实现
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/netTest")
public String netTest() {
try {
//String url = "http://127.0.0.1:8080/statusCode3xx";
//String url = "http://127.0.0.1:8080/statusCode4xx";
//String url = "http://127.0.0.1:8080/statusCode5xx";
String url = "http://127.0.0.1:8080/timeout";
String result = restTemplate.getForObject(url, String.class);
logger.info(" result = " + result);
} catch (HttpClientErrorException e) {// 4xx
logger.error(" HttpClientErrorException , e = " + e.getMessage());
e.printStackTrace();
} catch (HttpServerErrorException e) {// 5xx
logger.error(" HttpServerErrorException , e = " + e.getMessage());
e.printStackTrace();
} catch (UnknownHttpStatusCodeException e) {
logger.error(" UnknownHttpStatusCodeException , e = " + e.getMessage());
e.printStackTrace();
}catch(HttpStatusCodeException e){
logger.error(" HttpStatusCodeException , e = " + e.getMessage());
e.printStackTrace();
}catch(ResourceAccessException e){//timeout
logger.error(" ResourceAccessException , e = " + e.getMessage());
e.printStackTrace();
}
return "netOK";
}
@RequestMapping("/statusCode3xx")
public ResponseEntity<String> returnStatusCode3XX() {
return new ResponseEntity<String>(" error ", HttpStatus.USE_PROXY);
}
@RequestMapping("/statusCode4xx")
public ResponseEntity<String> returnStatusCode4XX() {
return new ResponseEntity<String>(" error ", HttpStatus.UNAUTHORIZED);
}
@RequestMapping("/statusCode5xx")
public ResponseEntity<String> returnStatusCode5XX() {
return new ResponseEntity<String>(" error ", HttpStatus.SERVICE_UNAVAILABLE);
}
@RequestMapping("/timeout")
public String returnTimeout() {
try {
Thread.sleep(9*1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return " ok ";
}