restTemplate学习
异常处理器 | 功能 |
---|---|
ResponseErrorHandler | 异常处理器接口 |
DefaultResponseErrorHandler | restTemplate默认的异常处理器,处理客户端和服务端异常 |
ExtractingResponseErrorHandler | 根据HttpMessageConverter对象转换器 将HTTP错误响应转换RestClientException 需要指定ResponseErrorHandler |
NoOpResponseErrorHandler | 对异常不进行处理 |
ResponseErrorHandler
ResponseErrorHandler是restTemplate的异常接口
restTemplate中所有的异常处理器都是实现的它
public interface ResponseErrorHandler {
/**
* 判断请求是否异常
* 返回false表示不管response的status是多少都返回没有错
* 这里可以自己定义那些status code你认为是可以抛Error
* 当然也可以根据response的body来判断
*/
boolean hasError(ClientHttpResponse response) throws IOException;
/**
* 这里面可以实现你自己遇到了Error进行合理的处理
*/
void handleError(ClientHttpResponse response) throws IOException;
/**
* 默认的异常处理器
* 这里最终调用的还是上面的方法
* 当然可以重写这个方法
*/
default void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
handleError(response);
}
}
DefaultResponseErrorHandler
DefaultResponseErrorHandler实现的ResponseErrorHandler
它是restTemplate的默认异常处理器
hasError
方法—判断是否为异常
进入isError
里可以看到restTemplate默认判断400一类(客户端)和500一类(服务端)为异常
handleError
—对客户端和服务端错误抛出异常
restTemplate是怎么调用的DefaultResponseErrorHandler
以下类容都是在RestTemplate类中
- restTemplate发送请求之后,调用handleResponse()方法
- 进入handleResponse()方法,调用的
getErrorHandler()
- 进入
getErrorHandler()
–调用的本类的errorHandler
- 再查看这个参数发现,restTemplate一开始建立后就是直接new 的一个DefaultResponseErrorHandler
- 扩展
由此可以明确的知道restTemplate是怎么使用的DefaultResponseErrorHandler
那么我们怎么把自定义异常处理器的设置为默认的异常处理器呢?
在RestTemplate中有一个异常处理器的setter方法,可以设置
如果你使用的是RestTemplateBuilder
构建的restTemplate,在RestTemplateBuilder中有一个errorHandler
可以设置
ExtractingResponseErrorHandler
NoOpResponseErrorHandler
顾名思义:不进行处理
实现类在RestTemplate中
如何应用
当使用指定的凭据新建@link testresttemplate实例时,默认设置为这个处理器
自定义异常处理器
public class CustomErrorHandler implements ResponseErrorHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomErrorHandler.class);
/**
* 返回false表示不管response的status是多少都返回没有错
* 这里可以自己定义那些status code你认为是可以抛Error
* Indicate whether the given response has any errors.
* <p>Implementations will typically inspect the
* {@link ClientHttpResponse#getStatusCode() HttpStatus} of the response.
*
* @param response the response to inspect
* @return {@code true} if the response indicates an error; {@code false} otherwise
* @throws IOException in case of I/O errors
*/
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().value() != 200 && response.getStatusCode().value() !=302;
}
/**
* 这里面可以实现你自己遇到了Error进行合理的处理
* Handle the error in the given response.
* <p>This method is only called when {@link #hasError(ClientHttpResponse)}
* has returned {@code true}.
*
* @param response the response with the error
* @throws IOException in case of I/O errors
*/
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
/**
* 替代上面的方法
* Alternative to {@link #handleError(ClientHttpResponse)} with extra
* information providing access to the request URL and HTTP method.
*
* @param url the request URL
* @param method the HTTP method
* @param response the response with the error
* @throws IOException in case of I/O errors
* @since 5.0
*/
@Override
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
LOGGER.error("=======================ERROR============================");
LOGGER.error("DateTime:{}", DateUtil.generateTimeFormatter(response.getHeaders().getDate(),"yyyy-MM-dd HH:mm:ss"));
LOGGER.error("HOST:{},URI:{}", url.getHost(),url.getPath());
LOGGER.error("Method:{}", method.name());
LOGGER.error("Exception:{}", response.getStatusCode());
LOGGER.error("========================================================");
}
}