springresttemplate

RestTemplate - handle potential NullPointerException when response body is null


I'm writing client that calls some backend REST service. I'm sending Product object which will be saved in DB and returned in response body with generated 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()); 
}

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

I have looked examples over internet of using RestTemplate postFprEntity, getForEntity ... but didn't find any example that handle NPE. I suppose that if body of response cannot be set, it will be some exception thrown and status code 5xx.

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


Solution

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

    Yes, it is quite possible and totally depends on the server. Normally, some REST APIs and Spring REST Repositories will return 404 if resource is not found but better safe than sorry.

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

    Of course you should.

    You can check if responseEntity.hasBody() && responseEntity.getBody() != null. And from there either throw an Exception of your own or handle however you see fit.