devops
devops

Reputation: 9187

Setting throwExceptionIfNoHandlerFound has no effect in Spring 4.2.*

Setting throwExceptionIfNoHandlerFound has no effect in Spring 4.2.2. It is important for me since I have to send all responses as JSON.

I'm setting throwExceptionIfNoHandlerFound in my AppInitializer like that:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    [...]

    @Override
    protected void customizeRegistration(Dynamic registration) {
        boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
        if(!done) throw new RuntimeException();
    }
}

It seems to work because DispatcherServlet#noHandlerFound throwing Exception like expected:

// 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);
    }
}

But then (it is very confusing!) EVERY exception get catched and resolved to an error view. So it is not possible to handle the NoHandlerFoundException by using Spring-@ExceptionHandler

Question:

I'm sure, it is very nice and useful feature, but is it any way to detect an 404 error to send a custom response instead of default html error page?

Upvotes: 3

Views: 8559

Answers (1)

rpvilao
rpvilao

Reputation: 1116

It seems to happen when we override to use the default servlet handling. Answered here

Upvotes: 1

Related Questions