RestTemplate在連接失敗的時候搁胆,會直接拋出異常弥搞,我們可以通過設(shè)置
restTemplate.setErrorHandler(new CustomErrorHandler());
來處理異常。但是這種靈活度不夠渠旁,不能在業(yè)務(wù)發(fā)生點(diǎn)靈活處理攀例。
還有一種思路就是捕獲各種情況下的異常,之后根據(jù)異常類型就知道對應(yīng)的異常了顾腊。
HttpClientErrorException - 在HTTP狀態(tài)為4xx的情況下
HttpServerErrorException - 在HTTP狀態(tài)為5xx的情況下
UnknownHttpStatusCodeException - 如果HTTP狀態(tài)未知
ResourceAccessException - 請求超時粤铭,Spring將拋出該實(shí)例下的底層異常將是java.net.SocketTimeoutException。
代碼實(shí)現(xiàn)
@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 ";
}