1.前言
RestTemplate模块用来调用第三方接口
当调用接口抛错时,默认继承DefaultResponseErrorHandler
但许多场景下,我们不需要直接调用抛错,而是让流程继续
自定义异常
允许错误出现且不抛异常
public class RestThrowErrorHandler implements ResponseErrorHandler {
/**
* 无论调用第三方接口是否正常,都不抛异常
*
* @param clientHttpResponse
* @return
* @throws IOException
*/
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
return false;
}
/**
* 若上面的方法返回 true, 调用此方法处理异常
*
* @param clientHttpResponse
* @throws IOException
*/
@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
}
}
使用时修改默认设置
统一异常处理
restTemplate.setErrorHandler(new RestThrowErrorHandler());
//采取统一异常处理,自定义异常处理
ResponseEntity<RancherToken> tokenResponseEntity =
restTemplate.postForEntity(url, req, RancherToken.class);
if (!tokenResponseEntity.getStatusCode().is2xxSuccessful()) {
throw new BaseException(tokenResponseEntity.getBody().toString());
//统一抛异常
}