Leo*_*ivì 6 java error-handling spring spring-mvc spring-boot
我有一个简单的Spring MVC应用程序,其中我想使用处理所有未映射的url @ControllerAdvice。这是控制器:
@ControllerAdvice
public class ExceptionHandlerController {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404() {
return "exceptions/404page";
}
}
Run Code Online (Sandbox Code Playgroud)
尽管如此,每次都会获得Whitelabel错误页面。
我尝试使用RuntimeException.class,HttpStatus.BAD_REQUEST并扩展了类NoHandlerFoundException但没有用。
有什么建议么?
小智 7
要使其工作,您需要throwExceptionIfNoHandlerFound在 DispecherServlet上设置属性。你可以这样做:
spring.mvc.throwExceptionIfNoHandlerFound=true
Run Code Online (Sandbox Code Playgroud)
在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();
}
}
Run Code Online (Sandbox Code Playgroud)
当然,在您的情况下,上述课程可能会更复杂。
| 归档时间: |
|
| 查看次数: |
1472 次 |
| 最近记录: |