开发者

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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜