Asynchronous exception handling with bluebird promises

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.


After dealing with the same scenario and needs you are describing, i've discovered zone.js , an amazing javascript library , used in multiple frameworks (Angular is one of them), that allows us to handle those scenarios in a very elegant way.

A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs

Using your example code :

import 'zone.js'

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

Zone.current
  .fork({
    name: 'your-zone-name',
    onHandleError: function(parent, current, target, error) {
      // handle the error 
      console.log(error.message) // --> 'AJAJAJA'
      // and return false to prevent it to be re-thrown
      return false
    }
  })
  .runGuarded(async () => {
    await getPromise()
  })