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

我正在尝试为AJAX调用实现jQuery默认的HTTPerror handling程序。 我已经为通用应用程序错误实现了默认error handling程序,如下所示:

$(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函数,遗憾的是,这对我的应用程序来说不是一个可行的解决方案。

任何的想法? 谢谢!

你可以做到以下几点

 $.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?'); } });