【问题标题】:RestTemplate - handle potential NullPointerException when response body is nullRestTemplate - 当响应主体为空时处理潜在的 NullPointerException
【发布时间】:2017-12-26 11:08:24
【问题描述】:

我正在编写调用一些后端 REST 服务的客户端。我正在发送 Product 对象,该对象将保存在 DB 中,并在响应正文中返回生成的 productId。

public Long createProduct(Product product) {
  RestTemplate restTemplate = new RestTemplate();
  final String url = " ... ";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);

  HttpEntity<Product> productEntity = new HttpEntity<>(product, headers);

  try {                                     
    ResponseEntity<Product> responseEntity = restTemplate.postForEntity(url, productEntity, Product.class);
    Product product = responseEntity.getBody();
    return product.getProductId();
  } catch (HttpStatusCodeException e) {
    logger.error("Create product failed: ", e);
    throw new CustomException(e.getResponseBodyAsString(), e, e.getStatusCode().value()); 
}

如果productresponseEntity.getBody() 为空,这个product.getProductId() 看起来像潜在的NullPointerException,我应该以某种方式处理它吗?

我在互联网上查看了使用 RestTemplate postFprEntity、getForEntity 的示例......但没有找到任何处理 NPE 的示例。我想如果无法设置响应体,会抛出一些异常和状态码 5xx。

是否有可能当响应状态码为200时,那个body可以为空?

【问题讨论】:

  • 是的,这是可能的。这一切都取决于从服务器端发送的内容
  • 好的,谢谢。但是当我使用 curl 或 postman 调用此服务时,如果它返回状态 200,则总是有正文,即 Product json。
  • 不确定这里的问题是什么。让我总结一下我所说的。当响应代码为 200 时,body 可以为 null。为了处理这种情况,您需要在代码中通过检查它是否为 null 来处理它。但是如果从服务器端抛出异常而不是在返回 200 状态和正文为 null 的响应时抛出 5xx 异常

标签: spring resttemplate


【解决方案1】:

是否可以在响应状态码为 200 时,该 body 可以 空?

是的,这是很有可能的,完全取决于服务器。通常,如果找不到资源,一些 REST API 和 Spring REST Repositories 将返回 404,但总比抱歉更安全。

这个product.getProductId() 看起来像潜在的 NullPointerException 如果productresponseEntity.getBody() 为空,我应该处理吗 不知何故?

当然应该。

您可以检查 如果 responseEntity.hasBody() &amp;&amp; responseEntity.getBody() != null。然后从那里抛出您自己的异常或处理您认为合适的异常。

【讨论】:

    猜你喜欢
    • 2015-08-07
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多