Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird.js custom Error catch function, does not apply on the first promise?

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;
like image 394
Daniel Avatar asked Jul 15 '14 11:07

Daniel


1 Answers

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

like image 95
Esailija Avatar answered Nov 14 '22 02:11

Esailija