Skip to content
Advertisement

Error handling inside addEventListener callback

How do developers structure their programs if they want to have a top-level error handling function?

The immediate thought that came into my mind was to wrap a try..catch to the main function, however, this does not trigger errors from callbacks?

JavaScript
JavaScript

Advertisement

Answer

In javascript you can override global onerror, catching most of the errors:

JavaScript

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

In your case:

JavaScript

Some extra info: https://blog.sentry.io/2016/01/04/client-javascript-reporting-window-onerror

Added after questions if Promise would raise the error, lets test:

JavaScript

Result:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement