Curr195
Curr195

Reputation: 133

How do I tap into all console.error messages

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

listener.js

(function () {
  window.onerror = function (msg) {
    console.log("I got the error:", msg);
  };
})();

and

thrower.js

(function () {
  console.error("sample error");
})();

both are loaded as a static assets from within <head> section of the very basic

index.html

<!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:

index.js

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

Answers (3)

mplungjan
mplungjan

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

Molkan
Molkan

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

Drag13
Drag13

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

Related Questions