【发布时间】:2017-09-21 11:59:24
【问题描述】:
有没有办法挂钩所有类似于 jquery 的 $(document).ajaxError() 的 fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) ajax 调用错误?
我们使用 $(document).ajaxError() 来检测会话超时/失败并显示登录对话框。我想在收到失败响应后立即检测超时。
这里有一些代码:
$(document).ajaxError((event, jqxhr) => {
if (jqxhr.statusText === 'abort') {
return;
}
// Sometimes (even with /restapi/session), we get no jqxhr.responseJSON, but we do have jqxhr.responseText
let responseJSON = jqxhr.responseJSON;
if (!responseJSON && jqxhr.responseText) {
responseJSON = JSON.parse(jqxhr.responseText);
}
if (jqxhr.status === 401) {
if (!responseJSON) {
// https://sentry.zetta.net//zetta/prod-frontend/group/13631/
alert('API call\'s responseJSON is empty, and so is jqxhr.responseText. Check the Console logs for more info.');
console.error('jqxhr:', jqxhr, 'event:', event);
}
if (responseJSON.code === 1900) { // session expired
this.setState({ showExpirationModal: true });
} else {
// TODO: consider removing handling of these errors locally
// Currently we'd be showing 2 popups in some places: one with a "permission denied", and another with this error handler
// alert('Unauthorized');
}
} else if (jqxhr.status === 500) { // TODO: see if we should to all 500 errors in this global handler
if (responseJSON.code === 8017) { // maintenance mode
alert(responseJSON.message);
}
} else if (!navigator.onLine) {
this.setState({ showConnectionModal: true });
} else if (responseJSON === undefined) {
console.error(event, jqxhr);
}
}
我不确定 Fetch API 是否支持。
【问题讨论】:
-
你可以试试
$.ajaxSetup -
请更具体一些。见How to Ask ...和...minimal reproducible example
-
不,没有全局 ajax 错误处理程序(这是有充分理由的)
-
那么,您的意思是,真正的 问题是如何检测和处理 fetch 超时?为什么包括所有这些杂七杂八的东西和关于 jquery 的漫谈而不是仅仅问这个?
标签: javascript jquery ajax fetch-api