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?
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.
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.
RestTemplate restTemplate = new RestTemplate(); MyObject response = restTemplate. getForObject("xxxxx", MyObject. class, new Object[]{}); the type of response is now MyObject.
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.
Foo foo = null; try { foo = restTemplate.getForObject(url, Foo.class, vars); } catch (HttpClientErrorException ex) { if (ex.getStatusCode() != HttpStatus.NOT_FOUND) { throw ex; } }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With