Reputation: 4438
I am trying to catch errors that happens in the users web browser. I want the user to send a screenshot of the error, possibly including file, line numbers etc.
I hoped it would be rather simple and standardized now. But I wonder. With trial and error I came up with this:
window.addEventListener('error', function (e) {
console.log(e);
let error = e;
if (e.error) error = e.error;
let msg = "There was an error.";
msg += " Please go to https://somewhere.com/";
msg += " and post an image of this message. \n\nError: ";
if (error.message) {
msg += error.message;
} else {
msg += error;
}
if (error.stack) msg += "\n\n"+error.stack;
console.log(msg);
alert(msg);
});
Does it work? Hm, maybe, but not as I expected. Trying this from the console for example did not give me "test error" in the alert popup, but "Script error":
setTimeout(function(){throw "test error"}, 1000)
How should I do this? (I am only interested in newer browsers and actually just Chrome at the moment. Maybe Firefox and Edge later.)
EDIT: First summing up the answers so far. The most important thing is the difference between those two (only the second one gives a traceback in Chrome):
throw "some error"
throw Error("some error")
Now to the other half of the problem. Which errors are caught. I get this in the console, for example, but it never reaches my error handler above. Why? (This is from IndexedDB, using idb.js)
Uncaught (in promise) DOMException: Key already exists in the object store.
Upvotes: 1
Views: 1590
Reputation: 111
Okay, that html file seems to work fine:
<html>
<body>
<script>
window.addEventListener('error', (e) => {
console.log(e);
});
setTimeout(() => { throw 'Hello world'; }, 1000);
</script>
</body>
</html>
That should output the proper error to the console. However when I try to set up the handler in DevTools console directly and throw an error in timeout handler, I am getting 'Script error.'. It looks like Chrome thinks it is a same origin policy violation in the latter case.
Upvotes: 1
Reputation: 138557
You may need to throw an error :)
throw new Error("test error")
Upvotes: 1