Bluebird Promises and Domains

175 Views Asked by At

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?

1

There are 1 best solutions below

2
Yuri Zarubin On BEST ANSWER

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();
    });