I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error
I use spring 4.0 and java configuration. My working code is:
@ControllerAdvice
public class MyExceptionController {
@ExceptionHandler(NoHandlerFoundException.class)
public ModelAndView handleError404(HttpServletRequest request, Exception e) {
ModelAndView mav = new ModelAndView("/404");
mav.addObject("exception", e);
//mav.addObject("errorcode", "404");
return mav;
}
}
In JSP:
HTTP Status 404 - Page Not Found
For Init param config:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
}
Or via xml:
rest-dispatcher
org.springframework.web.servlet.DispatcherServlet
throwExceptionIfNoHandlerFound
true
See Also: Spring MVC Spring Security and Error Handling