Spring RestTemplate - Overriding ResponseErrorHandler

后端 未结 2 618
独厮守ぢ
独厮守ぢ 2020-12-17 16:04

I am calling a ReST service through RestTemplate and trying to override ResponseErrorHandler in Spring 3.2 to handle cust

相关标签:
2条回答
  • 2020-12-17 16:40

    Following link has useful information about Exception Flow for Spring ResponseErrorHandler .

    Adding code here, just in-case the blog is down:

    Code for ErrorHandler:

    public class MyResponseErrorHandler implements ResponseErrorHandler {
    
        private static final Log logger = LogFactory.getLog(MyResponseErrorHandler.class);
    
        @Override
        public void handleError(ClientHttpResponse clienthttpresponse) throws IOException {
    
            if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) {
                logger.debug(HttpStatus.FORBIDDEN + " response. Throwing authentication exception");
                throw new AuthenticationException();
            }
        }
    
        @Override
        public boolean hasError(ClientHttpResponse clienthttpresponse) throws IOException {
    
            if (clienthttpresponse.getStatusCode() != HttpStatus.OK) {
                logger.debug("Status code: " + clienthttpresponse.getStatusCode());
                logger.debug("Response" + clienthttpresponse.getStatusText());
                logger.debug(clienthttpresponse.getBody());
    
                if (clienthttpresponse.getStatusCode() == HttpStatus.FORBIDDEN) {
                    logger.debug("Call returned a error 403 forbidden resposne ");
                    return true;
                }
            }
            return false;
        }
    }
    

    Code for using it in RestTemplate:

    RestTemplate restclient = new RestTemplate();
    restclient.setErrorHandler(new MyResponseErrorHandler());
    ResponseEntity<String> responseEntity = clientRestTemplate.exchange(
                        URI,
                        HttpMethod.GET,
                        requestEntity,
                        String.class);
                    response = responseEntity.getBody();
    
    0 讨论(0)
  • 2020-12-17 16:44

    I don't see your RestTemplate code, but I assume you to set your ResponseErrorHandler for RestTemplate to use like:

    RestTemplate restClient = new RestTemplate();
    restClient.setErrorHandler(new MyResponseErrorHandler());
    

    The exception is indeed thrown in handleError method. You can find how to throw CustomException using CustomResponseHandler from one of my previous answers.

    0 讨论(0)
提交回复
热议问题