In my Spring Boot 2.2.x web application I need to intercept 404 errors so I can execute some custom logic before the error page is rendered or the json with error info is returned.
What's the correct way to achieve this?
At the moment I'm trying with a @ControllerAdvice
class, but I don't know which exception to handle with the @ExceptionHandler
method (if any is thrown)...
NOTE: I have already tried to intercept NoHandlerFoundException
, but this doesn't seem to work... (the handler is not triggered).
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public void handleException() {
System.out.println("It's a 404!");
}
}
I also enabled this in my application.properties
:
spring.mvc.throw-exception-if-no-handler-found=true
Any other suggestion?