如何将Spring的RestTemplate配置为在返回404状态时返回null

时间:2013-02-13 19:45:29

标签: java spring rest jaxb

我正在调用一个返回XML的REST服务,并使用Jaxb2Marshaller来封送我的类(例如FooBar等)。所以我的客户端代码如下:

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

当服务器端的查找失败时,它返回404以及一些XML。我最终得到UnmarshalException,因为它无法读取XML。

Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"exception"). Expected elements are <{}foo>,<{}bar>

回复的主体是:

<exception>
    <message>Could not find a Foo for ID 123</message>
</exception>

如何配置RestTemplate,以便{404}发生时RestTemplate.getForObject()返回null

3 个答案:

答案 0 :(得分:28)

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

答案 1 :(得分:0)

要捕获与服务器相关的错误,它将处理内部服务器错误,

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

答案 2 :(得分:0)

要捕获404 NOT FOUND错误,可以使用HttpClientErrorException.NotFound

[1:224, 1:224]