try/catch
can not handle errors in asynchronous functions.
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.)
精彩评论