How to Catch all JavaScript Errors and Send them to the Server?


JavaScript is a famous programming language that is one of the core languages of the World Wide Web (WWW) alongside HTML and CSS. It allows the programmer to capture events and modify the Document Object Model (DOM). In this article we are going to learn how we can catch all JavaScript errors and send them to the server.

What is onerror?

onerror is an event that is fired whenever an error occurs while loading an external file or resource or some error occurs while executing a script.

Syntax

onerror = (event, source, lineno, colno, error) => {};

Parameters: The following is the description of the parameters mentioned in the syntax:

  • event: A string that includes an error message that can be read by humans.

  • source: A string providing the script's URL, which is what caused the problem.

  • lineno: An integer that contains the script file's line number where the problem occurred.

  • colno: An integer containing the script file's column number where the problem occurred.

  • error: The error object thrown.

Example

In the following example, I am going to access a variable a which is not defined anywhere in the code. This will cause a ReferenceError and with the use of onerror event I am going to capture the error

<!DOCTYPE html>
<html>
<head>
    <title>How to catch a ReferenceError with onerror?</title>
</head>
<body>
    <h4>How to catch a ReferenceError with onerror?</h4>
    <div id="result"> </div>
    <script>
        window.onerror = (event, url, line, column, error) => {
            let msg = "";
            msg += "Error: " + error;
            document.getElementById("result").innerHTML = msg;
        };
        let sum = a + 2;
    </script>
</body>
</html>

Algorithm

We are going to use the above mentioned onerror event to help us capture the errors. Once we have captured the error, we are going to make use of AJAX (Asynchronous JavaScript And XML) to send the data to the backend server. We are going to make use of the XMLHttpRequest object to help us send the request to the server. We can send any type of request to the server, but for the purposes of illustration I am going to send a POST request.

We are also going to define a server where we will send the data to. For the purposes of illustration, we are going to use a very simple express server with a single POST route. I have made use of middlewares: cors and bodyParser, to help me ease the reception of the data.

Let us try to understand this with the help of an example:

Example

Step 1: First we will define the HTML file.

<!DOCTYPE html>
<html>
<head>
   <title>How to catch all JavaScript errors and send them to the server?</title>
</head>
<body>
   <h4>How to catch all JavaScript errors and send them to the server?</h4>
   <div>
      <button id="main">SEND</button>
   </div>
</body>
</html>

Step 2: Now we will add some styling to the button.

<style>
   #main{
      border-radius: 10px;
   }
</style>

Step 3: Now we are going to define the logic to send the error to the server.

<script>
   let data = [];
   window.onerror = (event, url, line, column, error) => {
      let err = {
         line: line,
         column: column,
         msg: error.message,
      }
      data.push(err);
   };
   let button = document.getElementById("main");
   button.onclick = () => {
      let jsondata = JSON.stringify(data);
      let xhr = new XMLHttpRequest();
      let url = "http://localhost:5000/";
      xhr.open('POST', url, true);
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(jsondata)
   }
   let sum = a + 2;
</script>

Step 4: We will now define the server to receive the data.

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express();
const port = 5000;

var jsonParser = bodyParser.json();

app.use(cors());

app.post("/", jsonParser, (req, res) => {
   console.log(req.body);
});

app.listen(port, () => {
   console.log(`Example app listening on port ${port}`);
});

After you have performed all the steps, the final code should look something like this:

Frontend

<!DOCTYPE html>
<html>

<head>
   <title>How to catch all JavaScript errors and send them to the server?</title>
   <style>
      #main{
         border-radius: 10px;
      }
   </style>
</head>

<body>
   <h4>How to catch all JavaScript errors and send them to the server?</h4>
   <div>
      <button id="main">SEND</button>
   </div>
   <script>
      let data = [];
      window.onerror = (event, url, line, column, error) => {
         let err = {
            line: line,
            column: column,
            msg: error.message,
         }
         data.push(err);
      };
      let button = document.getElementById("main");
      button.onclick = () => {
         let jsondata = JSON.stringify(data);
         let xhr = new XMLHttpRequest();
         let url = "http://localhost:5000/";
         xhr.open('POST', url, true);
         xhr.setRequestHeader("Content-Type", "application/json");
         xhr.send(jsondata)
      }
      let sum = a + 2;
   </script>
</body>

</html>

Backend

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const app = express();
const port = 5000;

var jsonParser = bodyParser.json();

app.use(cors());

app.post("/", jsonParser, (req, res) => {
   console.log(req.body);
});

app.listen(port, () => {
   console.log(`Example app listening on port ${port}`);
});

Output

Example app listening on port 5000
[ { line: 34, column: 19, msg: 'a is not defined' } ]

Conclusion

In this article, we saw how with the help of a combination of XMLHttpRequest object and onerror event we can capture the errors as well as send them to the server. Once we receive the error on the server side we can have a strategy to give proper error messages to the user so that he/she can act accordingly.

Updated on: 12-Sep-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements