zoukankan      html  css  js  c++  java
  • springboot restTemplate.exchange 自定义异常ErrorHandler转发

        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);
        }
    
    
    -- 沉着,冷静,bug总会解决,未来道路很光明。
  • 相关阅读:
    30-语言入门-30-分数加减法
    29-语言入门-29-两点距离
    bootstrapcss3触屏滑块轮播图
    input输入样式,动画
    HTML5夜空烟花绽放动画效果
    精美留言、评论框,带微博表情
    Sublime Text 3汉化中文版
    直播英国脱欧各国反应?谁将是最大赢家?
    品牌关键字的重要性?是什么呢
    网站收录之网络推广
  • 原文地址:https://www.cnblogs.com/dadadajiong/p/15131790.html
Copyright © 2011-2022 走看看