vegemite4me
vegemite4me

Reputation: 6856

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

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?

Upvotes: 27

Views: 26962

Answers (3)

aqel
aqel

Reputation: 485

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;
}

Upvotes: 6

Arunkumar Arjunan
Arunkumar Arjunan

Reputation: 382

to capture server related error, this will handle internal server error,

}catch (HttpServerErrorException e) {
        log.error("server error: "+e.getResponseBodyAsString());
        ObjectMapper mapper = new ObjectMapper();
        EventAPIResponse eh = mapper.readValue(e.getResponseBodyAsString(), EventAPIResponse.class);
        log.info("EventAPIResponse toString "+eh.toString());

Upvotes: 0

Tim
Tim

Reputation: 1174

Foo foo = null;
try {
    foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException ex)   {
    if (ex.getStatusCode() != HttpStatus.NOT_FOUND) {
        throw ex;
    }
}

Upvotes: 34

Related Questions