简体   繁体   中英

Is there a way to “re-initialize” JavaScript after an error occurred?

We are currently using the following code to track javascript errors on our website:

window.onerror = function(message) {
    log(message);
};

The log-function in the code above displays the error message within the console for developers but not for regular users. We are thinking about displaying some kind of information for regular users and then to reload the page after the user confirms the message. It would however be better if we could figure out a way to make sure that javascript continues to work even after an error has occurred. So we are wondering if there is a way to "re-initialize" javascript to start over after an error has occurred. Any help would be appreciated. Thanks

Sorry if you've already tried this, but did you try a "try catch" block?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

This will allow it to encounter an error, and then move on. In the "catch" block you could do something with error, but you can also just run other code as well after the error has occurred.

There is no built-in way to re-initialize your code (other than reloading the page), but here is a way you could do it:

Save a copy of the object key names in the window object. Wrap your starting code in a function and call the function once on startup. If you ever detect an error, delete all key-value pairs from the window object that were not saved in the original copy; this will delete all global vars. Finally, call your initialize function again.

This may have some complications when implementing, but should work most of the time.

As @That'sIs JustCrazy said, left over event listeners may be a problem, so you will also need a way to reset the DOM. You can save a copy of the original contents of your html tag at the beginning, const savedHTML = document.getElementsByTagName("html")[0].innerHTML . Then run document.getElementsByTagName("html")[0].innerHTML = savedHTML . I do remember reading somewhere that deleting elements with event listeners will cause memory leaks on IE, but on other browsers it is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM