覆盖特定状态代码的jQuery缺省ajaxError

时间:2017-03-06 11:03:14

标签: javascript jquery ajax

我试图为AJAX调用实现jQuery默认HTTP错误处理程序。我已经为通用应用程序错误实现了默认错误处理程序,如下所示:

$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
    switch (jqXHR.status) {
        case 403:
            console.log('Forbidden, go away!');
            break;
        case 404:
            console.log('Resource not found :O');
            break;
        case 422:
            console.log('Unprocessable entity.');
            break;
        case 500:
            console.log('Someone have to pay for this!');
            break;
        default:
            console.log('Anyone knows what is going on here?');
    }
});

现在我想要实现的是在单个AJAX调用中覆盖特定的状态代码。例如

$.ajax({
    ...
    error: function(jqXHR, textStatus, errorThrown) {
         if(jqXHR.status === 404){
             console.log('The requested unicorn is actually missing');
         }
    }
})

现在,如果我按上面所示实现,将显示两条消息

>The requested unicorn is actually missing
>Resource not found :O

虽然我只想获得The requested unicorn is actually missing消息。

在单个AJAX调用设置中设置global: false标志意味着忽略该AJAX调用中的所有全局AJAX函数,遗憾的是,这对我的应用程序来说不是一个可行的解决方案。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作

$.ajax({
    handleErrors: [404],
    ...
    error: function(jqXHR, textStatus, errorThrown) {
        if(jqXHR.status === 404){
            console.log('The requested unicorn is actually missing');
        }
    }
});

然后在您的全局处理程序中检查是否处理了错误

$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
    if (settings.handleErrors && settings.handleErrors.indexOf(jqXHR.status) !== -1) {
        return;
    }
    switch (jqXHR.status) {
        case 403:
            console.log('Forbidden, go away!');
            break;
        case 404:
            console.log('Resource not found :O');
            break;
        case 422:
            console.log('Unprocessable entity.');
            break;
        case 500:
            console.log('Someone have to pay for this!');
            break;
        default:
            console.log('Anyone knows what is going on here?');
    }
});