6

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.

2 Answers 2

17

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks !! That was what I was looking for :)
By chance do you know if it is possible to get the stack trace from the event object? because I am only able to get the "reason"
I found how to do it, I just added all the possible arguments to onerror
-3
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
}

5 Comments

Thanks for answering. But please, read the whole question, I am looking something for uncaught exceptions. I comment your solution in the last paragraph
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.
I was going to give you a -1 but you only have 1 HP...
@ozanmuyes You are supposed to vote on the answer, not the user.
@gre_gor You are definitely right yet the answer has already necessary enough minus points. So didn't bother :shrug:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.