2013-02-13 85 views
13

我打電話給返回XML的REST服務,並使用Jaxb2Marshaller來編組我的類(例如Foo,Bar等)。所以我的客戶端代碼如下所示:如何配置Spring的RestTemplate在返回404 HTTP狀態時返回null

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。由於無法讀取XML,我最終得到了一個UnmarshalException

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()回報null如果發生了404?

+0

'getForObject',默認情況下應該拋出一個'HttpClientErrorException' 404.你怎麼配置你的'RestTemplate'? – 2017-01-12 21:39:53

+0

@SotiriosDelimanolis我無法再訪問代碼,但是您所描述的默認行爲聽起來像我當時所期待的。 (我應該養成在未來的問題中陳述版本的習慣。) – vegemite4me 2017-01-13 18:00:51

回答

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

Better do 'if(ex.getStatusCode()!= HttpStatus.NOT_FOUND){{ }' – vdimitrov 2017-01-09 22:52:11

+0

編輯,謝謝 – Tim 2017-01-11 19:12:22