Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Spring's RestTemplate to return null when HTTP status of 404 is returned

Tags:

I am calling a REST service that returns XML, and using Jaxb2Marshaller to marshal my classes (e.g. Foo, Bar, etc). So my client code looks like so:

    HashMap<String, String> vars = new HashMap<String, String>();     vars.put("id", "123");      String url = "http://example.com/foo/{id}";      Foo foo = restTemplate.getForObject(url, Foo.class, vars); 

When the look-up on the server side fails it returns a 404 along with some XML. I end up getting an UnmarshalException thrown as it cannot read the XML.

Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"exception"). Expected elements are <{}foo>,<{}bar> 

The body of the response is:

<exception>     <message>Could not find a Foo for ID 123</message> </exception> 

How can I configure the RestTemplate so that RestTemplate.getForObject() returns null if a 404 happens?

like image 748
vegemite4me Avatar asked Feb 13 '13 19:02

vegemite4me


People also ask

How do you handle exceptions in RestTemplate?

Default Error Handling By default, the RestTemplate will throw one of these exceptions in the case of an HTTP error: HttpClientErrorException – in the case of HTTP status 4xx. HttpServerErrorException – in the case of HTTP status 5xx. UnknownHttpStatusCodeException – in the case of an unknown HTTP status.

What is difference between getForObject and getForEntity in RestTemplate?

For example, the method getForObject() will perform a GET and return an object. getForEntity() : executes a GET request and returns an object of ResponseEntity class that contains both the status code and the resource as an object. getForObject() : similar to getForEntity() , but returns the resource directly.

What is the return type for RestTemplate?

RestTemplate restTemplate = new RestTemplate(); MyObject response = restTemplate. getForObject("xxxxx", MyObject. class, new Object[]{}); the type of response is now MyObject.

Does RestTemplate support all HTTP methods?

Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods.


2 Answers

Foo foo = null; try {     foo = restTemplate.getForObject(url, Foo.class, vars); } catch (HttpClientErrorException ex)   {     if (ex.getStatusCode() != HttpStatus.NOT_FOUND) {         throw ex;     } } 
like image 69
Tim Avatar answered Sep 21 '22 15:09

Tim


To capture 404 NOT FOUND errors specifically you can catch HttpClientErrorException.NotFound

Foo foo; try {     foo = restTemplate.getForObject(url, Foo.class, vars); } catch (HttpClientErrorException.NotFound ex) {     foo = null; } 
like image 21
aqel Avatar answered Sep 20 '22 15:09

aqel