Alex
Alex

Reputation: 11579

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?

Upvotes: 1

Views: 1367

Answers (1)

Abel Pastur
Abel Pastur

Reputation: 1965

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,

Upvotes: 1

Related Questions