繁体   English   中英

Servlet Ajax全局异常处理

[英]Servlet Ajax global exception handling

我有一个AJAX调用的全局处理程序

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

如果出现错误,我的servlet过滤器会发送一个特定的错误

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

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

你会建议做点什么吗?

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

因为我认为每个浏览器中的responseText都不同。

响应正文可以通过xhr.responseText

但是, HttpServletResponse#sendError() (< - 单击链接以自己读取Javadoc)将使用servletcontainer的默认错误页面模板或您在web.xml定义的自定义错误页面模板。 这是一个HTML文档,因此您必须自己解析。

根据您对其他答案的评论,您似乎正在使用Tomcat并检索其默认错误页面; 该消息可用作第二个<p>第一个<u>元素。 所以这应该做:

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

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

您只需要记住,这种方式与(默认)错误页面的标记紧密相关。 更好的是不使用HttpServletResponse#sendError() ,但只需通过HttpServletResponse#setStatus()设置状态(< - 是,单击它以读取javadoc,答案就在那里)并将错误消息写入响应正文:

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

这样xhr.responseText就完全unavailableimage

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

在我的项目中,我正在使用此函数来调试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);
            }
        }
    });

所以使用你的代码,你可以测试x.responseText包含'unavailableimage',但是通过错误代码测试它并且错误消息更好;)

获取响应错误消息的另一种方法是使用: var responseText = $.httpData(xhr)具体取决于您的JQuery版本(<1.5.2)

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

暂无
暂无

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

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