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?

try {
  main();
} catch(error) {
  alert(error)
}

function main() {
  
  // This works
  throw new Error('Error from main()');
  
  document.querySelector('button').addEventListener('click', function() {
   // This doesn throw
   throw new Error ('Error from click callback');
  })
  
}
<button>
  Click me to see my callback error
</button>

Advertisement

Answer

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

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

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

In your case:

    window.onerror = function(message, source, lineno, colno, error) { 
        console.error(message);
        alert(message);
        return false
    };
    
    function main() {
      
      // This works
      throw new Error('Error from main()');
      
      document.querySelector('button').addEventListener('click', function() {
       // This doesn throw
       throw new Error ('Error from click callback');
      })
    }
    
    main();

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:

window.onerror = (message, source, lineno,colno,error)=>{
    console.error(`It does!, ${message}`);
};
const aFn = ()=>{
    return new Promise((resolve)=>{
        setTimeout(()=>{
            throw new Error("whoops")
        }, 3000);
    });
}
aFn();

Result:

VM1163:2 It does!, Script error.
window.onerror @ VM1163:2
error (asynchroon)
(anoniem) @ VM1163:1
VM1163:7 Uncaught Error: whoops
    at <anonymous>:7:19
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement