How do you create a global error handler for an es

2019-04-25 05:15发布

问题:

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.