Handle custom exceptions using @ExceptionHandler

Viewed 62

I have a class that catches exceptions using the Spring annotation @ExceptionHandler and this class support some custom exceptions as well. I would like that when I raise the exception CustomRuntimeException in this way throw new CustomRuntimeException(args...);, it will be caught and handled in the following method:

@ControllerAdvice
public class CutomExceptionManager {

    // code
    
    @ExceptionHandler({CustomRuntimeException.class})
    @ResponseBody
    private ResponseEntity<ErrorResource> handleCustomException(CustomException e, HttpServletRequest request, HttpServletResponse response) {
        logger.error("unhandled exception: ", (Exception)e);
        
        // other code
    }
    
}

This doesn't work.

1 Answers

As mentioned in the comments by @Tom Elias, the method should be protected or public to be taken in account by Spring.

As an example, the following code is working.

@ExceptionHandler(ControllerException.class)
public ResponseEntity<ControllerException> handleControllerException(ControllerException controllerException) {
    log.error(controllerException.getFullMessage(), controllerException);
    return new ResponseEntity<>(controllerException, HttpStatus.valueOf(controllerException.getStatus()));
}

BTW, no need to add the @ResponseBody annotation to the method.

Related