How to easily handle all errors in javascript asynchronous functions?

try/catch cannot handle errors in asynchronous functions.
Of course, you can handle it if I write try/catch in every asynchronous function, but this is unrealistic.

window.onerror can handle errors in asynchronous functions.
But window.onerror catches all the errors in the window.
I just want to handle all errors only in the asynchronous (as well as synchronous) functions of the javascript application (e.g. games) in the window.
And if the error only occurs in the javascript application, I want to show the error message and stop the application.
I want to do nothing for errors from the application.

+4
source share
1 answer

It doesn't seem to be able to distinguish between script errors and other errors. If you just want to catch your own exception types, then you can define your own exception constructor and deduce all your exceptions from it. Then check window.onerror to see if the object is retrieved from your custom constructor (and return true, if so, to fix the error or otherwise return false).

I think the most reliable way to do this would be to surround each asynchronous function in try / catch (although you say you don't want to do this). You can just make it an idiom; surround each asynchronous function in try / catch and call the catch lock with a function that handles the error accordingly. Or better yet, make an idiom in which the async function performs an additional β€œcallback” to the failure that it causes if an error occurs. Thus, the async caller can specify an asynchronous error handler. (This approach is used by the GWT framework, on the one hand.)

+1
source

All Articles