Spring MVC - RestTemplate launch exception when http 404 happens

前端 未结 5 1254
野性不改
野性不改 2020-12-30 19:48

I have a rest service which send an 404 error when the resources is not found. Here the source of my controller and the exception which send Http 404.

@Contr         


        
5条回答
  •  悲&欢浪女
    2020-12-30 20:32

    You can create your own RestTemplate wrapper which does not throw exceptions, but returns a response with the received status code. (You could also return the body, but that would stop being type-safe, so in the code below the body remains simply null.)

    /**
     * A Rest Template that doesn't throw exceptions if a method returns something other than 2xx
     */
    public class GracefulRestTemplate extends RestTemplate {
        private final RestTemplate restTemplate;
    
        public GracefulRestTemplate(RestTemplate restTemplate) {
            super(restTemplate.getMessageConverters());
            this.restTemplate = restTemplate;
        }
    
        @Override
        public  ResponseEntity getForEntity(URI url, Class responseType) throws RestClientException {
            return withExceptionHandling(() -> restTemplate.getForEntity(url, responseType));
        }
    
        @Override
        public  ResponseEntity postForEntity(URI url, Object request, Class responseType) throws RestClientException {
            return withExceptionHandling(() -> restTemplate.postForEntity(url, request, responseType));
        }
    
        private  ResponseEntity withExceptionHandling(Supplier> action) {
            try {
                return action.get();
            } catch (HttpClientErrorException ex) {
                return new ResponseEntity<>(ex.getStatusCode());
            }
        }
    }
    

提交回复
热议问题