Search code examples
javascriptnode.jspromisebluebirdnode.js-domains

Bluebird Promises and Domains


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?


Solution

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