I am developing a Rest API in spring boot. Which of the following is the best way to handle when an instance of resource not found ?
@GetMapping(value="/book/{id}")
public ResponseEntity<Book> getBook(@PathVariable String id){
Book book = bookService.getBook();
// Which is best Approach for resource instance not found ?
if(book == null) {
// This one
return new ResponseEntity<>(book, HttpStatus.NO_CONTENT);
//OR
return new ResponseEntity<>(book, HttpStatus.NOT_FOUND);
//OR
throw new DataNotFoundException("Book with id " + id + " Does not exist");
}
return new ResponseEntity<>(book , HttpStatus.OK);
}
I am clear about that when a collection of resource not found in Db then to pass an empty collection instead of null but I am not clear what to do with an instance of resource.
I have also read on StackOverflow that HttpStatus.NOT_FOUND
should be used when a Resource under the criteria cannot exist instead of do not exist in the Db.
What is best approach to handle this ?