1

I try to intercept custom exception with @ControllerAdvice annotation.

This is code:

@ControllerAdvice(basePackages = "{com.ciro.cotroller}")
@RestController
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {TodoNotFoundException.class})
    public final ResponseEntity<ExceptionResponse> todoNotFoundException(TodoNotFoundException exception){
        ExceptionResponse exceptionResponse = new ExceptionResponse(exception.getMessage(), "custom details");
        return new ResponseEntity<ExceptionResponse>(exceptionResponse,HttpStatus.NOT_FOUND);
    }
}

This is my exception:

package com.ciro.exception;

public class TodoNotFoundException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public TodoNotFoundException() {
        throw new RuntimeException("An custom error is raised!");
    }
}

But default entity response is returned.

ciro
  • 771
  • 1
  • 8
  • 30

1 Answers1

1

I changed the code in this way and all works fine.

public TodoNotFoundException() {
    super();
}

First error was in the exception's constructor. I need to invoke super method and not throws runtime exception.

@ControllerAdvice("com.ciro.cotroller")

The second is base package.

ciro
  • 771
  • 1
  • 8
  • 30