Fetch equivalent to jquery's $(document).ajaxError()

时间:2017-04-24 17:21:55

标签: javascript jquery ajax fetch-api

Is there a way to hook into all of the fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) ajax call errors similar to jquery's $(document).ajaxError()?

We're using $(document).ajaxError() to detect Session Timeout/failures and present a Login dialog. I would like to detect timeouts as soon as I get a failed response.

Here's some code:

    $(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);
        }
    }

I'm not sure if the Fetch API supports this.

1 个答案:

答案 0 :(得分:0)

从OP链接的文件

  

请注意,jQuery.ajax()规范与Promise不同   主要有两种方法要牢记:

     
      
  • 即使响应是HTTP 404或500,fetch() 返回的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)); 也不会拒绝HTTP错误状态。相反,它会   正常解决(ok状态设置为false),它只会   拒绝网络故障或任何事情阻止了请求   完成。
  •   

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

attr_accessor

jsfiddle https://jsfiddle.net/wgwd9hk3/