原因就在那里,在DispatcherServlet
课堂上;它发送错误响应而无需调用异常处理程序(默认情况下)。
从 4.0.0.RELEASE 开始,可以使用 throwExceptionIfNoHandlerFound 参数简单地更改此行为:
设置在没有找到该请求的 Handler 时是否抛出 NoHandlerFoundException。然后可以使用 HandlerExceptionResolver 或@ExceptionHandler
控制器方法捕获此异常。
XML配置:
<servlet>
<servlet-name>rest-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
基于Java的配置:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
...
}
然后NoHandlerFoundException
可以这样处理:
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
// return whatever you want
}
}