26

我正在调用一个返回 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>

如果发生 404 ,我该如何配置RestTemplate以便RestTemplate.getForObject()返回?null

4

3 回答 3

35
Foo foo = null;
try {
    foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException ex)   {
    if (ex.getStatusCode() != HttpStatus.NOT_FOUND) {
        throw ex;
    }
}
于 2013-07-11T21:31:54.253 回答
4

要专门捕获 404 NOT FOUND 错误,您可以捕获HttpClientErrorException.NotFound

Foo foo;
try {
    foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException.NotFound ex) {
    foo = null;
}
于 2020-04-20T11:20:47.013 回答
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());
于 2019-10-28T09:49:53.547 回答