简体   繁体   English

Servlet Ajax全局异常处理

[英]Servlet Ajax global exception handling

I have a global handler for my AJAX calls 我有一个AJAX调用的全局处理程序

$.ajaxSetup({
    error: function(xhr, textStatus, errorThrown) {
             //do something 
    }
});

And in case of an error my servlet filter sends a specifc error 如果出现错误,我的servlet过滤器会发送一个特定的错误

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {

    if(somethingwrong()) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unavailableimage");    
    }
}

Would you recommend to do something like 你会建议做点什么吗?

$.ajaxError({
    error: function(xhr, textStatus, errorThrown) {
        if (xhr.status == 408) {
            //doSomething
        }
        else if xhr.responseText.contains("unavailableimage"){
            //doSomething
        }
    }
}); 

Because I think the responseText is different in every browser. 因为我认为每个浏览器中的responseText都不同。

The response body is available by xhr.responseText . 响应正文可以通过xhr.responseText

However, the HttpServletResponse#sendError() ( <-- click the link to read the Javadoc yourself) will use the servletcontainer's default error page template or your custom error page template as you've definied in web.xml . 但是, HttpServletResponse#sendError() (< - 单击链接以自己读取Javadoc)将使用servletcontainer的默认错误页面模板或您在web.xml定义的自定义错误页面模板。 This is a HTML document which you thus have to parse yourself. 这是一个HTML文档,因此您必须自己解析。

As per your comment on the other answer, you seem to be using Tomcat and retrieving its default error page; 根据您对其他答案的评论,您似乎正在使用Tomcat并检索其默认错误页面; the message is available as first <u> element of the second <p> . 该消息可用作第二个<p>第一个<u>元素。 So this should do: 所以这应该做:

var errorMessage = $(xhr.responseText).filter('p:eq(1)').find('u').text();

if (errorMessage == 'unavailableimage') {
    // ...
}

You only need to keep in mind that you're this way tight coupled to the markup of the (default) error page. 您只需要记住,这种方式与(默认)错误页面的标记紧密相关。 Better is to not use HttpServletResponse#sendError() , but just set the status by HttpServletResponse#setStatus() ( <-- yes, click it to read javadoc, the answer was in there) and write the error message to the response body yourself: 更好的是不使用HttpServletResponse#sendError() ,但只需通过HttpServletResponse#setStatus()设置状态(< - 是,单击它以读取javadoc,答案就在那里)并将错误消息写入响应正文:

response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().write("unavailableimage");

This way the xhr.responseText is exactly unavailableimage . 这样xhr.responseText就完全unavailableimage

if (xhr.responseText == 'unavailableimage') {
    // ...
}

In my projects, I'm using this function for debugging ajax : 在我的项目中,我正在使用此函数来调试ajax:

$.ajaxSetup({
        error:function(x,e){
            if(x.status==0){
                alert('You are offline!!\n Please Check Your Network.');
            }else if(x.status==404){
                alert('Requested URL not found.');
            }else if(x.status==500){
                alert('Internal Server Error.\n'+x.responseText););
            }else if(e=='parsererror'){
                alert('Error.\nParsing JSON Request failed.');
            }else if(e=='timeout'){
                alert('Request Time out.');
            }else {
                alert('Unknow Error.\n'+x.responseText);
            }
        }
    });

so with your code, you can test if the x.responseText contains 'unavailableimage', but testing it by error code and error message is better ;) 所以使用你的代码,你可以测试x.responseText包含'unavailableimage',但是通过错误代码测试它并且错误消息更好;)

Another way to get only the response error message is to use : var responseText = $.httpData(xhr) depending of your version of JQuery (< 1.5.2) 获取响应错误消息的另一种方法是使用: var responseText = $.httpData(xhr)具体取决于您的JQuery版本(<1.5.2)

Or using json : var responseText = $.parseJSON(x.responseText); 或者使用json: var responseText = $.parseJSON(x.responseText);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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