简体   繁体   English

Spring MVC:如何在返回错误页面/响应之前拦截 404?

[英]Spring MVC: how to intercept 404 before returning error page/response?

In my Spring Boot 2.2.x web application I need to intercept 404 errors so I can execute some custom logic before the error page is rendered or the json with error info is returned.在我的 Spring Boot 2.2.x Web 应用程序中,我需要拦截 404 错误,以便我可以在呈现错误页面或返回带有错误信息的 json 之前执行一些自定义逻辑。

What's the correct way to achieve this?实现这一目标的正确方法是什么?

At the moment I'm trying with a @ControllerAdvice class, but I don't know which exception to handle with the @ExceptionHandler method (if any is thrown)...目前我正在尝试使用@ControllerAdvice类,但我不知道使用@ExceptionHandler方法处理哪个异常(如果有的话)...

NOTE : I have already tried to intercept NoHandlerFoundException , but this doesn't seem to work... (the handler is not triggered).注意:我已经尝试拦截NoHandlerFoundException ,但这似乎不起作用......(未触发处理程序)。

@ControllerAdvice
public class ErrorHandler {
    @ExceptionHandler(NoHandlerFoundException.class)
    public void handleException() {
        System.out.println("It's a 404!");
    }
}

I also enabled this in my application.properties :我还在我的application.properties启用了这个:

spring.mvc.throw-exception-if-no-handler-found=true

Any other suggestion?还有什么建议吗?

I finally found the solution (or part of it) in this question: Custom exception handler for NoHandlerFoundException is not working without @EnableWebMvc我终于在这个问题中找到了解决方案(或其中的一部分):没有 @EnableWebMvc,NoHandlerFoundException 的自定义异常处理程序不起作用

By default Spring doesn't throw an exception for 404 errors.默认情况下,Spring 不会为 404 错误抛出异常。 You need to enable this property in application.properties (or yaml):您需要在application.properties (或 yaml)中启用此属性:

spring.mvc.throw-exception-if-no-handler-found=true

But you also need to set this property:但您还需要设置此属性:

spring.mvc.static-path-pattern: /static

This restriction prevents Spring to search for static contents matching the missing path/handler.此限制阻止 Spring 搜索与缺少的路径/处理程序匹配的静态内容。

Now you can intercept a NoHandlerFoundException as usual with @ExceptionHandler .现在,您可以拦截NoHandlerFoundException像往常一样@ExceptionHandler

NOTE Before setting the spring.mvc.static-path-pattern property I tried to add @EnableWebMvc to a configuration class in my project: this way the NoHandlerFoundException was thrown but I obviously lost all the Spring Boot autoconfigurations.注意在设置spring.mvc.static-path-pattern属性之前,我尝试将@EnableWebMvc添加到我的项目中的配置类:这样抛出NoHandlerFoundException但我显然丢失了所有 Spring Boot 自动配置。

Use NoHandlerFoundException .使用NoHandlerFoundException This maps to 404 in spring boot.这映射到 Spring Boot 中的 404。

In the same class you use @ControllerAdvice implement ErrorController .在同一个类中,您使用@ControllerAdvice实现ErrorController

@ControllerAdvice
public class ControllerAdvice implements ErrorController {

    @RequestMapping("/error")
    public ResponseEntity<Map> handleError(HttpServletResponse response) {
        Map errorMapJson = new HashMap();

        if(response.getStatus() == HttpStatus.NOT_FOUND.value()) {
            errorMapJson.put("type", "404 Error");
        }

        return new ResponseEntity<Map>(errorMapJson, HttpStatus.NOT_FOUND);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM