Promise统一异常处理

时间:2022-06-16
本文章向大家介绍Promise统一异常处理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

现在前端和后端的交互过程中,很多时候都使用fetch和promise。 例如一个简化版本的从后台取得数据的方法如下

function getData(url) {
  return fetch(url).then(response => {
    if (response.ok) {
      return response;
    } else {
      throw new Error('error');
    }
  });
}

然后在其他地方调用即可

getData('projects').then(data => {
  console.log(data);
});

getData('users').then(data => {
  console.log(data);
});

但是上面没有对异常进行处理,为了进行方便的统一异常处理,可以修改返回的promise对象的then方法,自动将统一的错误处理handler加入。

function onError() {
  console.log('global error handler');
}

function getData(url) {
  const promise = fetch(url).then(response => {
    if (response.ok) {
      return response;
    } else {
      throw new Error('error');
    }
  });
  promise.oldThen = promise.then;
  promise.then = (onFulfilled, onRejected) => {
    return promise.oldThen(onFulfilled, onRejected || onError);
  };

  return promise;
}

调用的时候可以选择自定义的handler还是使用默认的

getData('projects').then(data => {
  console.log('use data' + data);
});

getData('roles').then(data => {
  console.log('use data' + data);
});

getData('users').then(data => {
  console.log('use data' + data);
}, () => {
  console.log('do my self');
});