Spring MVC - RestTemplate launch exception when http 404 happens

前端 未结 5 1252
野性不改
野性不改 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:38

    Since it's 2018 and I hope that when people say "Spring" they actually mean "Spring Boot" at least, I wanted to expand the given answers with a less dust-covered approach.

    Everything mentioned in the previous answers is correct - you need to use a custom ResponseErrorHandler. Now, in Spring Boot world the way to configure it is a bit simpler than before. There is a convenient class called RestTemplateBuilder. If you read the very first line of its java doc it says:

    Builder that can be used to configure and create a RestTemplate. Provides convenience methods to register converters, error handlers and UriTemplateHandlers.

    It actually has a method just for that:

    new RestTemplateBuilder().errorHandler(new DefaultResponseErrorHandler()).build();
    

    On top of that, Spring guys realized the drawbacks of a conventional RestTemplate long time ago, and how it can be especially painful in tests. They created a convenient class, TestRestTemplate, which serves as a wrapper around RestTemplate and set its errorHandler to an empty implementation:

    private static class NoOpResponseErrorHandler extends 
           DefaultResponseErrorHandler {
    
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
        }
    
    }
    

提交回复
热议问题