CodeBlanks Logo Icon CodeBlanks

Global error handling

JavaScript course · Intermediate · Lesson 104/134

Learn to collect uncaught errors with window.onerror and unhandledrejection.

Collecting uncaught errors

Errors that escape try/catch reach the browser console. With window.addEventListener('error', handler) you catch them centrally. The handler receives the error's message, filename and lineno. These listeners are the main way to forward real user errors to an error reporting service. This makes production issues visible.

window.addEventListener('error', (event) => {
  reportError(event.message, event.filename);
});

The unhandledrejection event

When a promise rejects and no .catch is attached, the unhandledrejection event fires. The handler reads the rejection reason from event.reason. The rejection reason is usually an Error object or a string. By listening to this event you can record and analyse uncaught promise errors just like sync errors.

window.addEventListener('unhandledrejection', (event) => {
  console.error('Rejected:', event.reason);
});

This event is the backbone of error reporting services.

Exercise Write global listeners

Write two event listeners. First, window.addEventListener('error', handler) sends event.message to the reportError function. Second, window.addEventListener('unhandledrejection', handler) sends event.reason to the reportError function.

Show example solution
window.addEventListener('error', (event) => {
  reportError(event.message);
});
window.addEventListener('unhandledrejection', (event) => {
  reportError(event.reason);
});

Test yourself

  1. Which event catches unhandled promise rejections?

    • window.onerror
    • unhandledrejection
    • beforeunload
    • DOMContentLoaded
    Show answer

    unhandledrejection — Correct! the unhandledrejection event catches rejections.

  2. Add the rejection event

    window.addEventListener(____, (event) => {
      logRejection(event.reason);
    });
    Show answer
    window.addEventListener('unhandledrejection', (event) => {
      logRejection(event.reason);
    });
  3. Match events to their sources

    error
    Sync runtime error
    unhandledrejection
    Unhandled promise
    event.message
    Error text
    event.reason
    Rejection reason

All lessons in Intermediate