从零实现axios(7.1小节-请求超时及网络错误处理)

307 阅读1分钟

请求超时、网络错误处理

我们在 xhr.js 文件中添加 请求超时网络错误 的监听器,它们的逻辑非常简单,就是如果超时和网络错误发生的时候,直接抛出一个错误对象并终止掉这个请求。

var transitionalDefaults = require('../defaults/transitional');

module.exports = function xhrAdapter(config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
    // ...

    // 处理网络错误
    request.onerror = function handleError() {
      // Real errors are hidden from us by the browser
      // onerror should only fire if it's a network error
      reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));

      request = null;
    };

    // 处理超时
    request.ontimeout = function handleTimeout() {
      var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
      var transitional = config.transitional || transitionalDefaults;
      if (config.timeoutErrorMessage) {
        // 我们可在配置中自定义超时信息
        timeoutErrorMessage = config.timeoutErrorMessage;
      }
      reject(new AxiosError(
        timeoutErrorMessage,
        transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
        config,
        request));

      request = null;
    };

  
    // ...
  });
};