简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM