Search code examples
javaspringspring-bootnullpointerexceptionresponse-entity

Should I do a check for null for a ResponseEntity<> object in Spring Boot?


I'm working with ResponseEntity<> in a Spring Boot project and I want to know if it's mandatory to check the responseBody object for null before calling getBody()?

For ex:

ResponseEntity<Customer> responseBody = customerClient.getCustomer(id);

I'm not sure if a ResponseEntity object could be null. Can I do directly Customer customer = responseBody.getBody(); or should I do a check for null before that?


Solution

  • No, you don't need to check if responseEntity is null.

    Spring is designed to always return a value inside responseEntity. What can be null, is the getBody() method that you call on responseEntity.

    You might want to take a look at the following: