Handle error 404 with Spring controller

后端 未结 5 561
再見小時候
再見小時候 2020-11-29 07:00

I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error

5条回答
  •  不知归路
    2020-11-29 07:29

    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

    The page you requested is not available. You might try returning to the ">home page.

    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

提交回复
热议问题