Bluebird.js custom Error catch function, does not

2019-03-20 15:51发布

I'm trying to use the custom error handlers of Bluebird.js.

In the example bellow the catch-all handler is called, not the MyCustomError handler, but when I moved the rejection into the then function (and resolved the firstPromise...), the MyCustomError handler is called. Why is that? got something wrong? Thanks.

var Promise = require('bluebird'),
debug = require('debug')('main');

firstPromise()
    .then(function (value) {
      debug(value);
    })
    .catch(MyCustomError, function (err) {
      debug('from MyCustomError catch: ' + err.message);
    })
    .catch(function (err) {
      debug('From catch all: ' + err.message);
    });

/*
 * Promise returning function.
 * */
function firstPromise() {
  return new Promise(function (resolve, reject) {
    reject(new MyCustomError('error from firstPromise'));
  });
}
/*
 *  Custom Error
 * */
function MyCustomError(message) {
  this.message = message;
  this.name = "MyCustomError";
  Error.captureStackTrace(this, MyCustomError);
}
MyCustomError.prototype = Object.create(Error.prototype);
MyCustomError.prototype.constructor = MyCustomError;

1条回答
Evening l夕情丶
2楼-- · 2019-03-20 16:38

Declare the error class before anything else and it will work (prototype assignments are not hoisted)

查看更多
登录 后发表回答