Reputation: 83
I have the following controller:
@PostMapping("/product/{id}")
void getProduct (@PathVariable UUID productId);
and id
is id from my database table. My ORM is Hibernate. How to return NOT_FOUND
if there is no such id
in the best way?
I know that I can:
void getProduct(@PathVariable UUID productId){
// check whether exists a file and throw NOT_FOUND if not.
}
I am looking better method to do it- it is very common situation in my project.
Upvotes: 0
Views: 43
Reputation: 757
A very common and effective pattern to you problem is the following where the service layer delegates the database not found case to an application specific exception and then a controller advisor handles the exception translation to a meaningful rest response. This is an old article @ spring.io which will give you even more suggestions.
The service bean:
@Service
class ResourceService {
@Autowired
ResourceDao dao;
Resource getById(UUID id) {
Resource res = dao.findById(id);
if (res != null) {
throw new MyNotFoundException();
}
return res;
}
}
The advisor bean:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = MyNotFoundException.class)
protected ResponseEntity<Object> handleConflict(MyNotFoundException ex, WebRequest request) {
String bodyOfResponse = "No resource with this id found.";
return handleExceptionInternal(ex, bodyOfResponse,
new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
Upvotes: 1