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);
    }

 


posted @ 2021-08-12 11:09  风中有朵云做的鱼  阅读(731)  评论(0编辑  收藏  举报