RestTemplate - 当响应主体为 null 时处理潜在的 NullPointerException

RestTemplate - handle potential NullPointerException when response body is null

我正在编写调用某些后端 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()); 
}

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

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

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

Is it possible when response status code is 200, that body can be null?

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

This product.getProductId() looks like potential NullPointerException if product i.e. responseEntity.getBody() is null, should I handle it somehow?

当然应该。

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