【问题标题】:How to configure Spring's RestTemplate to return null when HTTP status of 404 is returned如何配置 Spring 的 RestTemplate 以在返回 404 的 HTTP 状态时返回 null
【发布时间】:2013-01-29 11:33:41
【问题描述】:

我正在调用一个返回 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>

如果发生 404,我如何配置 RestTemplate 以便 RestTemplate.getForObject() 返回 null

【问题讨论】:

  • getForObject,默认情况下,应该抛出一个带有 404 的 HttpClientErrorException。你是如何配置你的 RestTemplate 的?
  • @SotiriosDelimanolis 我无法再访问代码,但您描述的默认行为听起来像我当时所期望的。 (我应该养成在以后的问题中说明版本的习惯。)

标签: java spring rest jaxb


【解决方案1】:
Foo foo = null;
try {
    foo = restTemplate.getForObject(url, Foo.class, vars);
} catch (HttpClientErrorException ex)   {
    if (ex.getStatusCode() != HttpStatus.NOT_FOUND) {
        throw ex;
    }
}

【讨论】:

    【解决方案2】:

    捕获服务器相关错误,这将处理内部服务器错误,

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

    【讨论】:

      【解决方案3】:

      要专门捕获 404 NOT FOUND 错误,您可以捕获 HttpClientErrorException.NotFound

      Foo foo;
      try {
          foo = restTemplate.getForObject(url, Foo.class, vars);
      } catch (HttpClientErrorException.NotFound ex) {
          foo = null;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 1970-01-01
        • 2017-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多