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

我与影子孤独终老i 提交于 2020-01-16 00:53:11

问题


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,



来源:https://stackoverflow.com/questions/17322855/how-to-handle-404-exception-invoked-by-ajax-spring-mvc-3-2-controlleradvice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!