[英]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 在Spring MVC中,如果我使用常规提交方式提交Web表单,则可以处理web.xml
中的404异常,
<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
? 但是如何拦截来自ajax调用的404
错误(可能使用@ControllerAdvice
)并将自定义异常传递给jquery
xhr.responseText
?
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: 然后,您可以在JavaScript中获取错误:
$.post("/servlet/wrong/url", function() {
alert("success");
})
.fail(function(jqXHR) {
alert(jqXHR.responseText);
});
Obviously this only works for request handled by your DispatcherServlet, 显然,这仅适用于您的DispatcherServlet处理的请求,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.