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

佐尔米

我正在编写调用一些后端 REST 服务的客户端。我正在发送 Product 对象,该对象将保存在数据库中并在响应正文中返回,并带有生成的 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()如果productieresponseEntity.getBody()为空,看起来像是潜在的 NullPointerException ,我应该以某种方式处理它吗?

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

当响应状态代码为 200 时,该主体可以为空吗?

乌鲁什T。

当响应状态代码为 200 时,该主体可以为空吗?

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

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

你当然应该。

您可以检查是否 responseEntity.hasBody() && responseEntity.getBody() != null. 从那里要么抛出你自己的异常,要么处理你认为合适的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

尝试使用RestTemplate获取对象列表时响应主体为空

尝试解析JSON时Spring RestTemplate响应主体为null

RestTemplate模拟提供NullPointerException

RestTemplate Spring boot 中的 NullPointerException MediaType

使RestTemplate流程响应主体不受状态影响

Spring @Autowired restTemplate为空

Spring RestTemplate发布响应

如何在 Spring Boot 中修复 RestTemplate NullPointerException?

错误:java.lang.NullPointerException 通过 RestTemplate 交换方法 - SpringBoot

如何在Spring RestTemplate中处理空响应

Spring Resttemplate异常处理

Spring RestTemplate处理状态为NO_CONTENT的响应时的行为

使用restTemplate的REST API的响应值为空

为什么RestTemplate GET响应应为XML时为JSON?

Spring RestTemplate:BadRequest 400,为空。在调用获取请求时

resttemplate getForObject地图响应类型

无法在RestTemplate中提取响应

改造2-响应状态为422时,响应主体为空(不可处理实体)

RestTemplate 收到的响应不在 json 中

如何模拟RestTemplate的Web服务响应?

无法使用RestTemplate解析REST响应

无法解析RestTemplate接收到的JSON响应

如何在Spring RestTemplate中记录响应?

如何从RestTemplate中读取响应标头?

Spring RestTemplate,在解析为Json之前拦截响应

处理图像加载 NullPointerException

图标处理抛出NullPointerException

将对象设置为空数组时出现 NullPointerException

检查数组是否为空时发生NullPointerException