Issue
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?
Solution
Foo foo = null;
try {
foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException ex) {
if (ex.getStatusCode() != HttpStatus.NOT_FOUND) {
throw ex;
}
}
Answered By - Tim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.