简体   繁体   English

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

[英]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).我正在调用一个返回 XML 的 REST 服务,并使用Jaxb2Marshaller来编组我的类(例如FooBar等)。 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.当服务器端的查找失败时,它会返回 404 以及一些 XML。 I end up getting an UnmarshalException thrown as it cannot read the XML.我最终得到一个UnmarshalException抛出,因为它无法读取 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?如何配置RestTemplate以便RestTemplate.getForObject()在发生 404 时返回null

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要专门捕获 404 NOT FOUND 错误,您可以使用 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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