简体   繁体   中英

How to handle 404 exception invoked by ajax, Spring MVC 3.2, @ControllerAdvice

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 ?

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM