Asynchronous exception handling with bluebird prom

2019-01-02 16:18发布

问题:

What is the best way to handle this scenario. I am in a controlled environment and I don't want to crash.

var Promise = require('bluebird');

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(function(){
                throw new Error("AJAJAJA");
        }, 500);
    });
}

var p = getPromise();
    p.then(function(){
        console.log("Yay");
    }).error(function(e){
        console.log("Rejected",e);
    }).catch(Error, function(e){
        console.log("Error",e);
    }).catch(function(e){
        console.log("Unknown", e);
    });

When throwing from within the setTimeout we will always get:

$ node bluebird.js

c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
                throw new Error("AJAJAJA");
                      ^
Error: AJAJAJA
    at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

If the throw occurs before the setTimeout then bluebirds catch will pick it up:

var Promise = require('bluebird');

function getPromise(){

    return new Promise(function(done, reject){
        throw new Error("Oh no!");
        setTimeout(function(){
            console.log("hihihihi")
        }, 500);
    });
}

var p = getPromise();
    p.then(function(){
        console.log("Yay");
    }).error(function(e){
        console.log("Rejected",e);
    }).catch(Error, function(e){
        console.log("Error",e);
    }).catch(function(e){
        console.log("Unknown", e);
    });

Results in:

$ node bluebird.js
Error [Error: Oh no!]

Which is great - but how would one handle a rogue async callback of this nature in node or the browser.

回答1:

Promises are not domains, they will not catch exceptions from asynchronous callbacks. You just can't do that.

Promises do however catch exceptions that are thrown from within a then / catch / Promise constructor callback. So use

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(done, 500);
    }).then(function() {
        console.log("hihihihi");
        throw new Error("Oh no!");
    });
}

(or just Promise.delay) to get the desired behaviour. Never throw in custom (non-promise) async callbacks, always reject the surrounding promise. Use try-catch if it really needs to be.



回答2:

Thank @Bergi. Now i know promise does not catch error in async callback. Here is my 3 examples i have tested.

Note: After call reject, function will continue running.

Example 1: reject, then throw error in promise constructor callback

Example 2: reject, then throw error in setTimeout async callback

Example 3: reject, then return in setTimeout async callback to avoid crashing

// Caught
// only error 1 is sent
// error 2 is reached but not send reject again
new Promise((resolve, reject) => {
  reject("error 1"); // Send reject
  console.log("Continue"); // Print 
  throw new Error("error 2"); // Nothing happen
})
  .then(() => {})
  .catch(err => {
    console.log("Error", err);
  });


// Uncaught
// error due to throw new Error() in setTimeout async callback
// solution: return after reject
new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("error 1"); // Send reject
    console.log("Continue"); // Print

    throw new Error("error 2"); // Did run and cause Uncaught error
  }, 0);
})
  .then(data => {})
  .catch(err => {
    console.log("Error", err);
  });


// Caught
// Only error 1 is sent
// error 2 cannot be reached but can cause potential uncaught error if err = null
new Promise((resolve, reject) => {
  setTimeout(() => {
    const err = "error 1";
    if (err) {
      reject(err); // Send reject
      console.log("Continue"); // Did print
      return;
    }
    throw new Error("error 2"); // Potential Uncaught error if err = null
  }, 0);
})
  .then(data => {})
  .catch(err => {
    console.log("Error", err);
  });


标签: