Search code examples
javascripterror-handlingdeveloper-toolsuncaught-exception

How to manage "uncaught exceptions" in JavaScript in order to show the error message in the user interface?


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.


Solution

  • 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