7

Bluebird 3.4.1 for promises, Chrome 56, Babel 6.23.1

Given:

  async login() {
    try {
      let response = await this.authservice.login('invalid-credentials');
    } catch (error) {

    }
  }

The above code simulates a 401 response error with a json object with the specific error message returned from the server which does trigger the catch statement. But instead of having to handle the error for each catch statement I would like to have a global error handler.

In non async functions I use the window.onerror event which works as expected. However this does not work for async functions.

I have also added events for

window.addEventListener('unhandledrejection')
window.addEventListener('rejectionhandled')

these events do not trigger for the above case(they do trigger for other cases). Instead bluebird returns "warning a promise was rejected with a non-error: [object Response]".

The this.authservice.login is using a library that uses the standard promise syntax versus async functions.

I can get the error to eventually bubble up to the unhandledrejection event if I throw a new error in the catch statement. However the above function is called from another function and I have to throw an error in both functions in order for the global unhandledrejection to fire.

In short I am trying to make a global error handler for all async/awaits and promises.

dan
  • 2,857
  • 6
  • 34
  • 60
  • 3
    Every async chain should have its own error handling (it's own catch). You simply can't properly handle errors from the top level. So, if you're asking this because you don't want to handle errors locally, that is a flawed set of thinking. Rejections needs to be handled in the code that is managing that promise, not as some higher level that has no idea what just happened of how to deal with it properly. If you want to use a common error handler for separate multiple functions, you can do that with a simple wrapper. – jfriend00 Feb 24 '17 at 23:09
  • Yes I was looking at not handling errors locally but what you said makes sense and I will just use a wrapper instead. I was a little confused on how the unhandledrejection and rejectionhandled worked but I have since got a better handle on things. Thanks. – dan Feb 25 '17 at 23:19

0 Answers0