Skip to content

Instantly share code, notes, and snippets.

  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
JavaScript: How to Deal with Unhandled Exceptions & Unhandled Promise Rejections in JavaScript

How to Deal with Unhandled Exceptions in JavaScript

The following code shows how you might create and report an error, and how it may be caught by adding a listener for the error event.



window.addEventListener('error', (event) => {
  // An uncaught exception occurred. It will be logged in the console.
  // Get the error properties from the error event object
  const { message, filename, lineno, colno, error } = event;
  // Output, if desired.
  console.log('Captured uncaught exception:', message, filename, lineno, colno, error.stack);

How to Deal with Unhandled Promise Rejections in JavaScript

Many environments (such as Node.js) report unhandled promise rejections to the console by default.

You can prevent that from happening by adding a handler for unhandledrejection events that—in addition to any other tasks you wish to perform—calls preventDefault() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code.

This works because unhandledrejection is cancelable.


// The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise 
// that has no rejection handler is rejected; typically, this is the window, but may also be a Worker.
// This is useful for debugging and for providing fallback error handling for unexpected situations.

window.addEventListener('unhandledrejection', (event) => {
  // code for handling the unhandled rejection
  // the event object has two special properties:
  // [object Promise] - The JavaScript Promise that was rejected.
  // Reference:
  // Error: Whoops! - A value or Object indicating why the promise was rejected, as passed to Promise.reject().
  // Reference:

  // Prevent the default handling (such as outputting the error to the console)
  // Reference:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment