首页 > 编程语言 > 详细

springboot restTemplate.exchange 自定义异常ErrorHandler转发

时间:2021-08-12 12:10:12      阅读:20      评论:0      收藏:0      [点我收藏+]

    spring微服务项目经常需要与其他服务交互对接,调用其他服务接口时异常原样抛出。参考网络其他博主的指导解决后记录

restTemplate.exchange 调用其他系统服务接口的时候报错捕获 实现
ResponseErrorHandler  


public class RestExceptionHandler implements ResponseErrorHandler {

    /**
     * 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 true;
    }

    /**
     * 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 {
        System.out.println("response.getStatusCode():::"+response.getStatusCode());
        System.out.println("response.getBody():::"+response.getBody());
    }

    /**
     * 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 {
        System.out.println("method.name():::"+method.name());
        System.out.println("url.getPath():::"+url.getPath());
        System.out.println("response.getStatusCode():::"+response.getStatusCode());
        System.out.println("response.getBody():::"+response.getBody());
    }
}

使用案例:

private ResponseEntity<String> route(RequestEntity requestEntity) {
        restTemplate.setErrorHandler(new RestExceptionHandler());
        return restTemplate.exchange(requestEntity, String.class);
    }

 

springboot restTemplate.exchange 自定义异常ErrorHandler转发

原文:https://www.cnblogs.com/dadadajiong/p/15131790.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!