处理 Bluebird 中的异常

Handling exception in Bluebird

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 in ApiError),我在这里做错了什么?

编辑:问题实际上是我没有返回 Bluebird promise 的实例,而是返回节点 Promise(使用 fetch),我通过将 fetch 包装在 Bluebird 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.

中解决了它