1

I have a issue with throwing an error inside of a bluebird promise. Take the following code:

var Promise = require('bluebird');
var domain = require('domain');

var problem = function() {
    return new Promise(function(resolve, reject){
        reject(new Error('Oops!'));
    });
};

domain.create()
    .on('error', function(e){
        console.log("Caught Error " + e.message)
        process.exit(1);
    })
    .run(function() {
        problem().done();
    });

I would expect to see Caught Error Oops! in the console. However it seems that the error is not caught inside of the domain and i'm seeing a fatal error and stack trace in the console.

Does anyone know why?

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Kinetic
  • 1,714
  • 1
  • 13
  • 38
  • 1
    Domains are deprecated, you shouldn't be using them. – Ben Fortune Apr 06 '16 at 11:00
  • That's not very helpful. Yes i understand that domains may be replaced in the future, however as of today almost 2 years after the request to deprecate them they are still in the core. Domains are still pending deprecation as nothing has yet materialized to replace the very specific functionality they provide. – Kinetic Apr 06 '16 at 12:01
  • This is an issue with bluebird, promises from the Q library function as expected. – Kinetic Apr 06 '16 at 14:38
  • Don't mix two technologies. And promises, and domains can handle your errors, but you should choose something one. You don't see error message, because bluebird handles it for you. When any error is raised in Promise chain or you rejected with error, all what you can it's catch error in `catch` handler and process error there. – alexmac Apr 06 '16 at 15:30

1 Answers1

1

The exception is actually being handled by Bluebird. Promise rejections are not the same as unhandled exceptions. If instead you create a real unhandled exception inside a setTimeout, which would therefore not be handled by Bluebird as it would be on a different stack, your domain will work as expected.

var Promise = require('bluebird');
var domain = require('domain');

var problem = function() {
    return new Promise(function(resolve, reject){
        setTimeout(function() {
            throw new Error('boom!');
        }, 1)

    });
};

domain.create()
    .on('error', function(e){
        console.log("Caught Error " + e.message)
        process.exit(1);
    })
    .run(function() {
        problem().done();
    });
Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33