3
In a REST service application with Spring, where should the exception handling/release take place? In the Controller or Service?
Example 1 - Handle in Controller (In this case I’m only 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- Handle 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 treating this Exception with a Controlleradvice through an Exceptionhandler of each exception.
What would be the most correct way to be working with exceptions?
In my opinion this should be dealt with in the Controller. Let’s imagine that at some point in the project the service method
findByfoo
need to return you a null object and take another logic, without being obligatory to play this exception. But this depends on case by case, let’s assume another situation, to register a certain entity X Oce needs to search for an entity Y and so so you can register X, in this case a treatment/exception launch in the service would be validated.– Erick Maia
@Erickmaia, in this case, wouldn’t the Controller be just an input port for my data via REST? And the question of validation, even the one that gave example, where returns a null object and needs to take another logic, do not know something related to business rule that stays in service?
– melpin