Spring MVC - RestTemplate launch exception when http 404 happens

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

    RESTTemplate is quite deficient in this area IMO. There's a good blog post here about how you could possibly extract the response body when you've received an error:

    http://springinpractice.com/2013/10/07/handling-json-error-object-responses-with-springs-resttemplate

    As of today there is an outstanding JIRA request that the template provides the possibility to extract the response body:

    https://jira.spring.io/browse/SPR-10961

    The trouble with Squatting Bear's answer is that you would have to interrogate the status code inside the catch block eg if you're only wanting to deal with 404's

    Here's how I got around this on my last project. There may be better ways, and my solution doesn't extract the ResponseBody at all.

    public class ClientErrorHandler implements ResponseErrorHandler
    {
       @Override
       public void handleError(ClientHttpResponse response) throws IOException 
       {
           if (response.getStatusCode() == HttpStatus.NOT_FOUND)
           {
               throw new ResourceNotFoundException();
           }
    
           // handle other possibilities, then use the catch all... 
    
           throw new UnexpectedHttpException(response.getStatusCode());
       }
    
       @Override
       public boolean hasError(ClientHttpResponse response) throws IOException 
       {
           return response.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR
             || response.getStatusCode().series() == HttpStatus.Series.SERVER_ERROR;
       }
    

    The ResourceNotFoundException and UnexpectedHttpException are my own unchecked exceptions.

    The when creating the rest template:

        RestTemplate template = new RestTemplate();
        template.setErrorHandler(new ClientErrorHandler());
    

    Now we get the slightly neater construct when making a request:

        try
        {
            HttpEntity response = template.exchange("http://localhost:8080/mywebapp/customer/100029",
                                            HttpMethod.GET, requestEntity, String.class);
            System.out.println(response.getBody());
        }
        catch (ResourceNotFoundException e)
        {
            System.out.println("Customer not found");
        }
    

提交回复
热议问题