【问题标题】:404 Exception not handled in Spring ControllerAdviceSpring ControllerAdvice 中未处理 404 异常
【发布时间】:2019-06-04 14:07:37
【问题描述】:

我有一个简单的 Spring MVC 应用程序,我想在其中使用 @ControllerAdvice 处理所有未映射的 url。 这是控制器:

@ControllerAdvice
public class ExceptionHandlerController {
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle404() {
        return "exceptions/404page";
    }
}

不过,每次都会得到 Whitelabel Error Page。

我尝试使用RuntimeException.classHttpStatus.BAD_REQUEST 并使用NoHandlerFoundException 扩展类,但没有用。

有什么建议吗?

【问题讨论】:

    标签: java spring spring-boot spring-mvc error-handling


    【解决方案1】:

    要使其工作,您需要在 DispecherServlet 上设置 throwExceptionIfNoHandlerFound 属性。你可以这样做:

    spring.mvc.throwExceptionIfNoHandlerFound=true
    

    application.properties 文件中,否则请求将始终转发到默认 servlet 并且永远会抛出 NoHandlerFoundException。

    问题是,即使使用此配置,它也不起作用。来自文档:

    请注意,如果 org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler 是 使用,则请求将始终转发到默认 servlet 在这种情况下永远不会抛出 NoHandlerFoundException。

    因为 Spring Boot 默认使用 org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,所以您必须使用自己的 WebMvcConfigurer 覆盖它:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @EnableWebMvc
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            // Do nothing instead of configurer.enable();
        }
    } 
    

    当然,在你的情况下,上面的类可能更复杂。

    【讨论】:

    • 使用 spring boot 2.0.2.RELEASE 这个解决方案不起作用。必须按照 zwlxt 的答案编写一个 ErrorController
    【解决方案2】:

    另一种方法是ErrorController

    @Controller
    public class MyErrorController implements ErrorController {
    
        @GetMapping("/error")
        public ModelAndView errorHandler(HttpServletRequest req) {
            // Get status code to determine which view should be returned
            Object statusCode = req.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
            // In this case, status code will be shown in a view
            ModelAndView mav = new ModelAndView("error_default");
            mav.addObject("code", statusCode.toString());
            return mav;
        }
    
        public String getErrorPath() {
            return "/error";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 2018-01-15
      • 2022-10-14
      • 2023-03-21
      • 2018-07-13
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多