Spring ControllerAdvice中未处理404异常 [英] 404 Exception not handled in Spring ControllerAdvice

查看:955
本文介绍了Spring ControllerAdvice中未处理404异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple Spring MVC application in which I want to handle all the unmapped urls using @ControllerAdvice. Here is the controller:

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

仍然,每次都会获得Whitelabel错误页面.

Still, every time get Whitelabel Error Page.

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

I tried using RuntimeException.class, HttpStatus.BAD_REQUEST and extending the class with NoHandlerFoundException but no use.

有什么建议吗?

推荐答案

要使其正常运行,您需要在DispecherServlet上设置throwExceptionIfNoHandlerFound属性.您可以执行以下操作:

To make it work, you need to set throwExceptionIfNoHandlerFound property on DispecherServlet. You can do that with:

spring.mvc.throwExceptionIfNoHandlerFound=true

application.properties文件中,否则请求将始终转发到默认servlet,并且将引发NoHandlerFoundException.

in application.properties file, otherwise the requests will always be forwarded to the default servlet and NoHandlerFoundException would ever be thrown.

问题是,即使使用此配置,它也不起作用.从文档中:

The problem is, even with this configuration, it doesn't work. From the documentation:

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

Note that if org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler is used, then requests will always be forwarded to the default servlet and NoHandlerFoundException would never be thrown in that case.

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

Because Spring Boot uses by default the org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler you'll have to override this using your own 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();
    }
} 

当然,上述情况在您的情况下可能会更复杂.

Of course, the above class might be more complicated in your case.

这篇关于Spring ControllerAdvice中未处理404异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆