How to handle 404 exception invoked by ajax, Sprin

2019-08-05 00:59发布

问题:

In Spring MVC, if I submit web form using normal submit I can handle 404 exception in web.xml as

    <error-page>
        <error-code>404</error-code>
        <location>404.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>404.jsp</location>
    </error-page>

But how to intercept 404 error from ajax call (probably using @ControllerAdvice) and pass custom exception to xhr.responseText in jquery?

回答1:

You could use a default controller for unmapped requests, and write your error in the response:

@Controller
public class DefaultController {

    @RequestMapping
    public void unmappedRequest(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.getWriter().write("404 error mesage");
    }
}

Then you can get the error in your javascript:

$.post("/servlet/wrong/url", function() {
     alert("success");
})
.fail(function(jqXHR) { 
     alert(jqXHR.responseText);
});

Obviously this only works for request handled by your DispatcherServlet,