设置throwExceptionIfNoHandlerFound
在 Spring 4.2.2 中无效。这对我很重要,因为我必须以 JSON 格式发送所有响应。
我throwExceptionIfNoHandlerFound
在我的AppInitializer中设置如下:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
[...]
@Override
protected void customizeRegistration(Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
它似乎有效,因为DispatcherServlet#noHandlerFound像预期的那样抛出异常:
// https://github.com/spring-projects/spring-framework/blob/4.2.x/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java#L1013
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
"] in DispatcherServlet with name '" + getServletName() + "'");
}
if (this.throwExceptionIfNoHandlerFound) {
throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
new ServletServerHttpRequest(request).getHeaders());
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
但是随后(这非常令人困惑!)每个异常都被捕获并解决为错误视图。所以不可能NoHandlerFoundException
通过使用Spring来处理 -@ExceptionHandler
问题:
我敢肯定,这是一个非常好的和有用的功能,但是有没有办法检测 404 错误来发送自定义响应而不是默认的 html 错误页面?