简体   繁体   English

如何处理Ajax,Spring MVC 3.2,@ ControllerAdvice调用的404异常

[英]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.

相关问题 Spring ControllerAdvice 中未处理 404 异常 - 404 Exception not handled in Spring ControllerAdvice @ControllerAdvice 不适用于 Spring 3.2 - @ControllerAdvice not working with Spring 3.2 如何使用@ControllerAdvice 和@ExceptionHandler 处理404 异常? - How to handle 404 exceptions using @ControllerAdvice and @ExceptionHandler? 即使我们在catch块中处理异常,如何使用@ControllerAdvice在Spring中处理异常 - How to handle exception in spring with @ControllerAdvice even though we are handling exception in catch block 如何覆盖专用于处理异常的 ControllerAdvice - How cover a ControllerAdvice dedicated to handle exception ControllerAdvice 有条件地处理异常 - ControllerAdvice conditionally handle exception Spring @ControllerAdvice异常处理程序返回404错误而不是视图 - Spring @ControllerAdvice exception handler returning 404 error instead of view Spring MVC @ControllerAdvice异常行为因异常源而异 - Spring MVC @ControllerAdvice exception behavior different based on Exception source Spring异常处理 - @ControllerAdvice无法处理HttpServletResponse#sendError() - Spring Exception Handling - @ControllerAdvice cannot handle HttpServletResponse#sendError() 如何使用java配置和没有Web.xml处理Spring MVC中的404页面未找到异常 - How to handle 404 page not found exception in Spring MVC with java configuration and no Web.xml
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM