设置throwExceptionIfNoHandlerFound在Spring 4.2中没有效果。*

时间:2016-01-21 22:43:45

标签: java spring spring-mvc http-status-code-404 handlerexceptionresolver

在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 catchedresolved to an error view。因此,使用Spring - NoHandlerFoundException

无法处理@ExceptionHandler

问题:

我确定,这是一个非常好用且有用的功能,但是有没有办法检测404错误来发送自定义响应而不是默认的html错误页面?

1 个答案:

答案 0 :(得分:1)

当我们覆盖使用默认的servlet处理时,似乎会发生这种情况。 Answered here