4

When a Uncaught Exception is thrown in some website or web application, an error appears in the Develper tools in each browser

uncaught_exception

In Electron for instance, if an uncaught exception, the developer can set a listener and do whatever I want with the error message:

process.on('uncaughtException', function (error) {
    // Handle the error
}

So, I wonder if there is an easy way to do the same in JavaScript. This could be useful in order to record and store common errors when the users are working, or in order to show what's happening to the user, who can send feedback to the developers.

Something like this could be shown instead

modal_exception

Sometimes, if an error occurs the app become in a unstable state where everything is frozen, and the user do not know why. I think informing about the error is important.

I found this Error JavaScript object. It can be manually thrown, but that can be used only when try and catch are used, and not for the uncaught exceptions, where the developer made some mistakes.

ChesuCR
  • 9,352
  • 5
  • 51
  • 114

2 Answers2

12

You can handle it as an event listener on window object.

window.onunhandledrejection = event => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
};

window.onerror = function(message, source, lineNumber, colno, error) {
  console.warn(`UNHANDLED ERROR: ${error.stack}`);
};

Or also like this:

 window.addEventListener('error', function(event) { ... })

You can read more about the unhandledrejection event on the MDN web docs here and the onerror event on the docs here

ChesuCR
  • 9,352
  • 5
  • 51
  • 114
Erin
  • 5,315
  • 2
  • 20
  • 36
-1
try {
  // YOUR CODE GOES HERE
} catch (e) {
 if ( e instanceof CustomExceptionError ) {
    // ...
  } else if ( e instanceof OtherExceptionError ) {
    // ...
  } else {
    // ...
  }
 //OR CALL THE ALERT BOX OR ANY OTHER UI CHANGE
}
  • Thanks for answering. But please, read the whole question, I am looking something for uncaught exceptions. I comment your solution in the last paragraph – ChesuCR Jun 19 '20 at 17:52
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Jun 19 '20 at 20:42
  • I was going to give you a -1 but you only have 1 HP... – ozanmuyes Jan 24 '23 at 21:10