I am trying to build my first spring boot based rest api and I'm trying to understand what are the common practices used to return 404 in case a resource was not found.
First of all I don't know if I should consider not finding a resource an "exceptional event" or just something that happens usually and my application should handle often.
Most of the solutions I found suggest the use of an annotated exception that tells the handlers to return a 404 in the case of a resource not found.
Eg:
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource not found")
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(Throwable cause) {
super(cause);
}
}
Now I am wondering, considering the fact that I use the simplest structure for my code:
- Controller
- Service
- Repository
where am I supposed to throw it? at the repository level? or just return null and throw the exception at the Controller level? would that be more efficient or it's just a bad practice?