Joey Yi Zhao
Joey Yi Zhao

Reputation: 42604

How to understand the event listeners execution on window object?

I am using window.addEventListener('message', fun) to register a few event listeners. What will happen if there is one event listener throws an exception? Whether other event listeners run as usual or are impacted by this exception? Is there a way to catch all exceptions outside fun function?

Upvotes: 0

Views: 48

Answers (1)

Unmitigated
Unmitigated

Reputation: 89442

Inside the fun event listener, if you think an exception may be thrown, you should catch it and handle it inside the function.

function fun(){
 try{
   //something that may throw an exception
 }catch(err){
   console.log(err.message);//log the exception message
   //handle exception
 }
}

If you want to catch all unhandled thrown exceptions, you can use window.onerror().

window.onerror = function(e){
 alert(e);
}
undefinedFunction();

Upvotes: 2

Related Questions