在Spring 4.2.2中设置throwExceptionIfNoHandlerFound
无效。这对我很重要,因为我必须以JSON发送所有回复。
我在我的 AppInitializer 中设置了throwExceptionIfNoHandlerFound
:
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);
}
}
然后(这非常令人困惑!)每个例外get catched和resolved to an error view。因此,使用Spring - NoHandlerFoundException
@ExceptionHandler
问题:
我确定,这是一个非常好用且有用的功能,但是有没有办法检测404错误来发送自定义响应而不是默认的html错误页面?