![](/img/trans.png)
[英]RestTemplate.postForObject Returns Null When ResponseEntity and Http Error Are Returned
[英]How to configure Spring's RestTemplate to return null when HTTP status of 404 is returned
我正在调用一个返回 XML 的 REST 服务,并使用Jaxb2Marshaller
来编组我的类(例如Foo
、 Bar
等)。 所以我的客户端代码如下所示:
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
以便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;
}
}
要专门捕获 404 NOT FOUND 错误,您可以使用 HttpClientErrorException.NotFound
Foo foo;
try {
foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException.NotFound ex) {
foo = null;
}
捕获与服务器相关的错误,这将处理内部服务器错误,
}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.