首先,我设置 throwExceptionIfNoHandlerFound
,使其可以引发异常
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
super.customizeRegistration(registration);
logger.info("正在注册服务...");
registration.setInitParameter("enableLoggingRequestDetails", "true");
registration.setInitParameter("throwExceptionIfNoHandlerFound","true");
}
然后,我写了一封信 ControllerAdvice
并使用 ExceptionHandler
处理异常,但它不起作用。那我该怎么办呢。
@ControllerAdvice
public class ErrorPageHandler {
private final Logger logger = Logger.getLogger(ExceptionHandler.class);
@ExceptionHandler(NoHandlerFoundException.class)
public String error404(NoHandlerFoundException ex){
logger.error(ex.getMessage(),ex.getCause());
return "404";
}
}
1条答案
按热度按时间jslywgbw1#
对于spring application.properties配置文件中的spring引导,必须配置以下内容:
那就行了。
在我的测试中,exceptionhandler是为超类exception执行的,我返回modelandview对象而不是字符串。但我想您这边的主要问题是,如果找不到处理程序,throw exception的配置就错了。
没有spring引导,您可以直接在中配置它
DispatcherServlet
,如下所示:除此之外,我还必须使用注解
@EnableWebMvc
然后它开始工作了。