Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeyBurzynski/dd4543b7078be54295a0eedd5212071c to your computer and use it in GitHub Desktop.
Save JoeyBurzynski/dd4543b7078be54295a0eedd5212071c to your computer and use it in GitHub Desktop.
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.

Demo: https://jsfiddle.net/joeyburzynski/x5wbe0jp/

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

window.addEventListener('error', (event) => {
  // An uncaught exception occurred. It will be logged in the console.
  event.preventDefault();
  
  // 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.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

// 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: https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent/promise
  console.log(event.promise); 
  
  // Error: Whoops! - A value or Object indicating why the promise was rejected, as passed to Promise.reject().
  // Reference: https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent/reason
  console.log(event.reason); 

  // Prevent the default handling (such as outputting the error to the console)
  // Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event#preventing_default_handling
  event.preventDefault();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment