【问题标题】:Fetch equivalent to jquery's $(document).ajaxError()获取相当于 jquery 的 $(document).ajaxError()
【发布时间】: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


【解决方案1】:

来自 OP 链接的文档

请注意,fetch 规范不同于 jQuery.ajax() 在 主要有两种方式要牢记:

  • fetch() 返回的Promise 不会拒绝 HTTP 错误状态,即使响应是 HTTP 404 或 500。相反,它会 正常解决(ok 状态设置为 false),它只会 拒绝网络故障或任何阻止请求 完成。

要获取状态码,返回Response.status

fetch("/path/to/server"/*, options object*/)
.then(response => ({headers: response.headers, code: response.status}))
.then(({headers, code}) => {
  for (let [key, value] of headers) {
    console.log(key, value)
  }
  console.log(code); // `403` at linked jsfiddle
  // if (code === /* code */) 
  // do stuff
})
.catch(err => console.log(err));

jsfiddle https://jsfiddle.net/wgwd9hk3/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
  • 2016-05-03
  • 2018-04-06
  • 1970-01-01
  • 2013-12-22
相关资源
最近更新 更多