我正在编写调用一些后端 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()
如果product
ieresponseEntity.getBody()
为空,这看起来像是潜在的 NullPointerException ,我应该以某种方式处理它吗?
我在互联网上查看了使用 RestTemplate postFprEntity、getForEntity ...的示例,但没有找到任何处理 NPE 的示例。我想如果无法设置响应体,则会抛出一些异常和状态代码 5xx。
当响应状态代码为 200 时,该主体可以为空吗?
当响应状态代码为 200 时,该主体可以为空吗?
是的,这是很有可能的,完全取决于服务器。通常,如果未找到资源,某些 REST API 和 Spring REST 存储库将返回 404,但总比抱歉更安全。
product.getProductId()
如果product
ieresponseEntity.getBody()
为空,这看起来像是潜在的 NullPointerException ,我应该以某种方式处理它吗?
你当然应该。
您可以检查是否 responseEntity.hasBody() && responseEntity.getBody() != null
. 从那里要么抛出你自己的异常,要么处理你认为合适的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句