1

Currently I have code such as:

window.onerror = function() {
    // Send some debug info about the defective error handling,
    // so that it may be fixed
};

To handle otherwise uncaught exceptions. Unfortunately this does not work for an async function. For example, if we call fooasync() below:

async function fooasync() {
    throw 'Catch me!';
}

Then the exception (if otherwise uncaught) won't be caught by the window.onerror catch-all...

I've done the requisite searching and have mostly come accross the answer, "it's not possible and anyway, it would be bad and you should catch it explicitly." I agree of course, but what if you have accidentally not wrapped an async function in a try...catch?

As an example of a valid use-case: I use the window.onerror handler to send me a debug email to let me know that something has gone horribly wrong for the person using my whatever. Great, at least I'm aware of the problem: Now I can fix the issue (and even fix the broken error-handling with an explicit try...catch). However, in the case of the async function, I have no way to even become aware of the issue (other than someone complaining that it's not working the way it's supposed to).

Is it possible to catch these async uncaught exceptions?

logidelic
  • 1,525
  • 15
  • 42
  • 2
    There are no uncaught exceptions in `async function`s - they always get caught and will reject the promise. Which then might cause an *unhandled rejection* - search for that term. – Bergi Mar 19 '19 at 20:57

1 Answers1

2

Similar to onerror, there is onunhandledrejection, which will be triggered if a Promise rejects and no handler is attached to it. Read on on MDN

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151