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

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


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