异常处理器 功能
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的默认异常处理器

  1. hasError方法—判断是否为异常
    spring学习之restTemplate的异常处理器
    进入isError里可以看到restTemplate默认判断400一类(客户端)和500一类(服务端)为异常
    spring学习之restTemplate的异常处理器
  2. handleError—对客户端和服务端错误抛出异常
    spring学习之restTemplate的异常处理器

restTemplate是怎么调用的DefaultResponseErrorHandler

以下类容都是在RestTemplate类中

  1. restTemplate发送请求之后,调用handleResponse()方法
    spring学习之restTemplate的异常处理器
  2. 进入handleResponse()方法,调用的getErrorHandler()
    spring学习之restTemplate的异常处理器
  3. 进入getErrorHandler()–调用的本类的errorHandler
    spring学习之restTemplate的异常处理器
  4. 再查看这个参数发现,restTemplate一开始建立后就是直接new 的一个DefaultResponseErrorHandler
    spring学习之restTemplate的异常处理器
  5. 扩展
    由此可以明确的知道restTemplate是怎么使用的DefaultResponseErrorHandler
    那么我们怎么把自定义异常处理器的设置为默认的异常处理器呢?
    在RestTemplate中有一个异常处理器的setter方法,可以设置
    spring学习之restTemplate的异常处理器
    如果你使用的是RestTemplateBuilder构建的restTemplate,在RestTemplateBuilder中有一个errorHandler可以设置
    spring学习之restTemplate的异常处理器

ExtractingResponseErrorHandler

spring学习之restTemplate的异常处理器

NoOpResponseErrorHandler

顾名思义:不进行处理
实现类在RestTemplate中

spring学习之restTemplate的异常处理器
如何应用
当使用指定的凭据新建@link testresttemplate实例时,默认设置为这个处理器
spring学习之restTemplate的异常处理器

自定义异常处理器

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("========================================================");
    }
}

spring学习之restTemplate的异常处理器
自定义异常例子源码地址

相关文章:

  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2021-07-06
  • 2022-12-23
  • 2021-07-16
  • 2021-11-28
猜你喜欢
  • 2021-09-18
  • 2021-12-24
  • 2021-09-20
  • 2021-06-30
  • 2021-07-07
  • 2021-09-29
相关资源
相似解决方案