簡體   English   中英

如何配置Spring的RestTemplate在返回404的HTTP狀態時返回null

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

我正在調用一個返回 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以便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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM