spring mvc 使用 @ControllerAdvice 捕获404异常

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

<error-page>
    
    <error-code>401error-code>
    <location>/general-error.htmllocation>
error-page>
<error-page>
    
    <error-code>403error-code>
    <location>/general-error.htmllocation>
error-page>
<error-page>
    
    <error-code>404error-code>
    <location>/Error404.htmllocation>
error-page>
<error-page>
    
    <error-code>500error-code>
    <location>/general-error.htmllocation>
error-page>
<error-page>
    
    <error-code>503error-code>
    <location>/general-error.htmllocation>
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 handleResourceNotFoundException(NoHandlerFoundException nhre) {
        logger.error(nhre.getMessage(), nhre);
        return new ResponseEntity("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

你可能感兴趣的:(spring)