I\'m trying to handle 404 error using an @ControllerAdvice
in a Spring MVC application totally configured using Javaconfig.
Spring MVC version is 4.1.5<
The solution is to extend AbstractAnnotationConfigDispatcherServletInitializer
and override this method:
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
OR this one:
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
And finally in your ControlerAdvice
use this:
@ExceptionHandler(NoHandlerFoundException.class)
public String error404(Exception ex) {
return new ModelAndView("404");
}
Workaround: Add @RequestMapping("/**")
@Controller
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@RequestMapping("/**")
public String handlerNotMappingRequest(HttpServletRequest request, HttpServletResponse response, HttpHeaders httpHeaders)
throws NoHandlerFoundException {
throw new NoHandlerFoundException("No handler mapping found.", request.getRequestURL().toString(), httpHeaders);
}
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handleControllerException(Throwable ex) {
logger.error("ErrorLog: ", ex);
return new ModelAndView("error/exception", "exceptionMsg", "ExceptionHandler msg: " + ex.toString());
}
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleNoHandlerFoundException(NoHandlerFoundException ex) {
logger.error("ErrorLog: ", ex);
return new ModelAndView("error/exception", "exceptionMsg", "NoHandlerFoundException msg: " + ex.toString());
}
}
Conclusion seems to be that setting throwExceptionIfNoHandlerFound to true does not throw an exception when no handler is found.
The solution is quite simple. From the javadoc @ DispatcherServlet.setThrowExceptionIfNoHandlerFound. It states here that a NoHandlerFoundException will never be thrown if DefaultServletHttpRequestHandler is used.
Solution hence is to remove the line
configurer.enable();
from your MvcConfiguration. The exception should fire now and your GlobalExceptionHandler should do the rest!