Reputation: 133
I'm trying to get all of the console.error
messages caught by dedicated error handler (which is supposed to trigger certain actions upon some specific error) and I'm trying to leverage window.onerror
callback for that purpose.
So far, I can't succeed even with my basic set-up, like
(function () {
window.onerror = function (msg) {
console.log("I got the error:", msg);
};
})();
and
(function () {
console.error("sample error");
})();
both are loaded as a static assets from within <head>
section of the very basic
<!DOCTYPE html>
<html>
<head>
<script src="assets/listen.js"></script>
<script src="assets/throw.js"></script>
</head>
<body>
here I go
</body>
</html>
and served by trivial express app:
import express from "express";
import { join } from "path";
const app = express();
app.use("/assets", express.static(join(__dirname, "public")));
app.use("/", (req, res) => {
res.sendFile(join(__dirname, "index.html"));
});
app.listen(9000, () => console.log("listen :9000"));
What I expect is getting sample error message echoed with custom prefix ('I got the error: '
) but there's no extra output in the console, so I assume, the sample error wasn't ever caught.
So, the question is: what exactly am I missing here?
Upvotes: 0
Views: 908
Reputation: 178421
console.error
is just console.log with Error:
in red. It is not a window.error so the thrower needs to do
(function () {
throw "sample error";
})();
You are able (but it is not recommended) to override the native console.error
Here I added a throw to the log
const err = console.error; // save the console.error method
console.error = str => { err(str); throw `'Throwing error':'${str}'`; };
console.error("My Error")
Upvotes: 2
Reputation: 564
As @Drag13 and @mplungjan console.log()
does not throw errors so you can't catch them using window.onerror
.
You have 2 choices to accomplish your goal, either change all of your console.error(error)
to throw error
or override the console.error
property to handle thus error logs, like this:
console.error = function (msg) {
console.log("I got the error:", msg);
};
Upvotes: 0
Reputation: 5998
(function () {
console.error("sample error");
})();
This is not throwing any error it's just logging some piece of text to console.
If you want to throw an error - u should use throw statement
(function () {
throw new Error('my error');
})();
Upvotes: 2