Handling Exception Services REST Spring

3

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?

    
asked by anonymous 21.03.2017 / 16:54

2 answers

3

The Controller only manages the flow of information and should not contain business rules and persistence in its content.

It would be more interesting to handle exceptions in the Service layer, so you would better manage future rule changes if you had to retrieve information from a DAO for example.

    
09.04.2017 / 01:35
1

As error handling as well as others, such as Logging, data access, etc ... are called cross-cutting interests (cross cutting concerns) , the most appropriate would be to handle the triggered exceptions through a Appearance . Spring allows you to set a @ControllerAdvice that would centralize the handling of triggered exceptions by Controllers .

Here is an example of error handling for ResourceNotFoundException :

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {        

//....

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe,
            HttpServletRequest request) {

        ErrorDetail errorDetail = new ErrorDetail();
        errorDetail.setTimeStamp(new Date().getTime());
        errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
        errorDetail.setTitle("Recurso não encontrado.");
        errorDetail.setDetail(rnfe.getMessage());
        errorDetail.setDeveloperMessage(rnfe.getClass().getName());

        return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
    }

//...

}

This ErrorDetail class is a class that can be customized to your application requirements:

public class ErrorDetail {

    private String title;
    private int status;
    private String detail;
    private long timeStamp;
    private String developerMessage;
    private Map<String, List<ValidationError>> errors = new HashMap<>();

//...
}
    
09.04.2017 / 04:22