Umang Gupta
Umang Gupta

Reputation: 16480

Catching errors in JS via eventListeners

Is there a way to handle errors like ReferenceError or TypeError in JS using event Listeners ? I know of try .. catch.. but that is not what I am looking for.

For example : I am looking for a method like document.onReferenceError or similar event listener.

Upvotes: 0

Views: 88

Answers (1)

jusopi
jusopi

Reputation: 6813

I assume you're trying to do global error handling. For errors you can't really tap into a type per se, but you can listen for all errors using:

window.onerror = function(message, source, lineno, colno, error) { ... }

For element specific errors you have a different function signature ("for historical reasons" - per docs)

element.onerror = function(event) { ... }

In either case you should be able to inspect the error or the event for a type of instanceof check.

//in case of global level checking
error instanceof ReferenceError //boolean

//in case of element level checking
event.type === <type you're looking for>  //boolean

docs - https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

Upvotes: 1

Related Questions