简体   繁体   中英

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 (eg 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?

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 use HttpClientErrorException.NotFound

Foo foo;
    try {
    foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException.NotFound ex)   {
    foo = null;
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM