window.onerror vs addEventListener error in JavaScript

JavaScript provides two primary mechanisms for globally intercepting uncaught runtime errors: the legacy window.onerror property and the modern window.addEventListener('error') method. While both listen for unhandled exceptions across your application, they differ significantly in how they handle multiple listeners, their ability to capture resource loading failures, and the signature of their callback parameters. Understanding these differences is essential for implementing robust client-side error tracking and monitoring.


Key Differences

1. Multiple Handlers vs. Single Handler

2. Resource Loading Errors

3. Callback Signatures

4. Preventing Default Browser Handling


Comparison Summary

Feature window.onerror window.addEventListener('error')
Listener Type Property assignment Event listener
Multiple Listeners No (overwrites previous) Yes
Resource Errors (<img>, <script>) Cannot capture Can capture (with useCapture: true)
Callback Arguments Separate parameters (message, source, etc.) Single ErrorEvent object
Prevent Default Handling return true; event.preventDefault();

When to Use Which