java - Spring ControllerAdvice 中未处理 404 异常

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

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

@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 扩展类,但没有用。

有什么建议吗?

最佳答案

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

spring.mvc.throwExceptionIfNoHandlerFound=true

application.properties 文件中,否则请求将始终被转发到默认的 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 覆盖它:

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();
    }
} 

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

关于java - Spring ControllerAdvice 中未处理 404 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116245/

相关文章:

java - Android将PGP集成到项目中

java - 如何在C#中实现java对实例化的重写?

java - JPA。如何返回 null 而不是 LazyInitializationException

java - 使用 Spring Boot 拦截请求和响应以获取/添加相关 ID

spring-boot - 如何修复Spring Boot Gradle:带有二进制文件的processResources

java - 有没有办法阻止本地主机中 mysql 数据库的入站和出站通信以进行测试?

java - 使用类别作为特征的线性回归

java - 兴趣点 : wrong number of cell per row form method getPhysicalNumberOfCells

java - jaeger 跟踪和 Spring Cloud OpenFeign

java - 如何根据底层数据库更改 Hibernate GenerationType 标识符