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);

サーバー側でのルックアップが失敗すると、XML とともに 404 が返されます。UnmarshalExceptionXMLを読み取れないため、スローされてしまいます。

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 に答える