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总会解决,未来道路很光明。
  • 相关阅读:
    css
    Git使用
    Github入门
    flask框架预备知识
    django框架预备知识
    JSON格式
    盒模型详解
    position属性详解
    float属性详解
    display属性详解
  • 原文地址:https://www.cnblogs.com/dadadajiong/p/15131790.html
Copyright © 2011-2022 走看看