Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to easily handle all errors in asynchronous functions of javascript?

try/catch can not handle errors in asynchronous functions.
Of course, it is possible to handle if I write try/catch in the every asynchronous functions but it is not realistic.

window.onerror can handle errors in asynchronous functions.
But window.onerror catches all errors in the window.
I just want handle all the errors only in asynchronous(and also synchronous) functions of a javascript application(for example, game) in the window.
And if a error occurs only in the javascript application, I want to show a error message and stop the application.
I want to do nothing for errors out of the application.

like image 760
js_ Avatar asked Nov 05 '22 18:11

js_


1 Answers

It sounds like it won't be possible to distinguish between script errors and other errors. If you just want to catch your own exception types, then you could define a custom Exception constructor and derive all of your own exceptions from that. Then have window.onerror check to see if the object is derived from your custom constructor (and return true if so, to suppress the error, or otherwise return false).

I think the most robust way of doing this would be to surround each async function in a try/catch (even though you say you don't want to do this). You can just make this an idiom; surround each async function in a try/catch and have the catch block call a function that handles the error appropriately. Or better yet, make an idiom where the async function takes an additional "failure" callback, which it calls if an error occurs. That way, the caller of an async function can specify an asynchronous error handler. (This approach is used by the GWT framework, for one thing.)

like image 108
mgiuca Avatar answered Nov 11 '22 05:11

mgiuca