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

情到浓时终转凉″ 提交于 2020-06-29 03:40:40

问题


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.


回答1:


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




回答2:


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
}


来源:https://stackoverflow.com/questions/62475654/how-to-manage-uncaught-exceptions-in-javascript-in-order-to-show-the-error-mes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!