In a REST service application with Spring, where should exception handling / posting occur? No Controller or Service?
Example 1 - Handling the Controller (In case I'm just returning a badrequest as an example)
@GetMapping
public ResponseEntity<Objeto> consultar(String foo) {
Objeto objeto;
try {
objeto = objetoService.findByFoo(foo);
if (objeto != null) {
return ResponseEntity.ok(objeto);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
Example 2- Treating in Service
public Objeto findByFoo(String foo) throws Exception {
Objeto objeto = objetoRepository.findByFoo(foo);
if(objeto != null){
return objeto;
} else {
throw new Exception();
}
}
The data are only illustrative. In case the service could be handling this exception with a ControllerAdvice through an ExceptionHandler of each exception.
What would be the most correct way to work with exceptions?