首页 文章

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

提问于
浏览
0

我正在编写调用一些后端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 ,即 responseEntity.getBody() 为空,那么 product.getProductId() 看起来像潜在的NullPointerException,我应该以某种方式处理它吗?

我看过使用RestTemplate postFprEntity,getForEntity的互联网示例......但没有找到任何处理NPE的示例 . 我想如果无法设置响应体,则会抛出一些异常并且状态码为5xx .

当响应状态代码为200时,该实体是否可以为空?

1 回答

  • 1

    当响应状态代码为200时,该实体是否可以为空?

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

    如果产品即responseEntity.getBody()为null,那么product.getProductId()看起来像潜在的NullPointerException,我应该以某种方式处理它吗?

    你当然应该 .

    你可以查看 responseEntity.hasBody() && responseEntity.getBody() != null . 从那里要么抛出你自己的例外,要么你认为合适 .

相关问题