Handling Exception Services REST Spring

Posted on

Question :

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)

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?


Answer :

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.


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 :

public class RestExceptionHandler extends ResponseEntityExceptionHandler {        


    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe,
            HttpServletRequest request) {

        ErrorDetail errorDetail = new ErrorDetail();
        errorDetail.setTimeStamp(new Date().getTime());
        errorDetail.setTitle("Recurso não encontrado.");

        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<>();



Leave a Reply

Your email address will not be published. Required fields are marked *