在蓝鸟中处理异常

Handling exception in Bluebird

本文关键字:异常 处理 蓝鸟      更新时间:2023-09-26
function ApiError(response) {
  this.message = 'API error';
  this.response = response;
}
ApiError.prototype = Object.create(Error.prototype);
ApiError.prototype.constructor = ApiError;
ApiError.prototype.name = 'ApiError';
export default ApiError;

我有这个自定义异常,我会在某个时候抛出它,但是当我试图在承诺中捕获它时,例如

import ApiError from './ApiError';
...
.catch(ApiError, (e) => {
    console.log('api error');
})
.catch((e) => {
    console.log(e); <= this is undefined(in ApiError)
});

错误被委托给通用捕获,错误说消息无法分配给未定义( this=undefined 在 ApiError 中(,我在这里做错了什么?

编辑:问题实际上是我没有返回蓝鸟承诺的实例,而是节点Promise(使用fetch(,我通过将获取包装在蓝鸟Promise.resolve中来解决它。

该错误听起来像您没有正确创建ApiError对象的实例。

当你抛出一个错误时,它应该是:

throw new ApiError(xxx);

请注意,必须使用的new。 错误的细节使其看起来像您没有使用new


或者,您可以更改 ApiError 构造函数的实现,以便您可以这样做;

throw ApiError(xxx);

但是,您必须更改 ApiError 以检测它是否使用 new 调用,如果没有,则调用new本身。

function ApiError(response) {
  if (!(this instanceof ApiError)) {
      return new ApiError(response);
  }
  this.message = 'API error';
  this.response = response;
}

或者,在 ES6 中,您可以使用new.target选项:

function ApiError(response) {
  if (!new.target) {
      return new ApiError(response);
  }
  this.message = 'API error';
  this.response = response;
}

问题实际上是我没有返回 Bluebird promise 的实例,而是 ES6 Promise(使用 fetch(,我通过将 fetch 包装在 Bluebird Promise.resolve 中来解决它。