spring mvc 使用 @ControllerAdvice 捕获404异常

如果使用web.xml来自定义404页面,可以在web.xml中添加error-page:

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

如果采用spring boot 或者AppInitializer来配置,需要在AppInitializer的实现类中重写createDispatcherServlet方法:

    @Override
    protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }

同时在@ControllerAdvice中添加方法:

    @ExceptionHandler
    public ResponseEntity<String> handleResourceNotFoundException(NoHandlerFoundException nhre) {
        logger.error(nhre.getMessage(), nhre);
        return new ResponseEntity<String>("Not Found", HttpStatus.NOT_FOUND);
    }

参考:
How to specify the default error page in web.xml?
How to handle 404 page not found exception in Spring MVC with java configuration and no Web.xml

猜你喜欢

转载自blog.csdn.net/jiangshanwe/article/details/72958360