How to Catch a ReferenceError with onerror?


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 see how we can catch ReferenceError with the help of onerror event.

What is ReferenceError?

A ReferenceError is a form of error that may occur when the program tries to access a variable or object that doesn't exist. This can occur when a variable's name is spelled incorrectly or when the user attempts to access an object that hasn't yet been initialised.

Example

<!DOCTYPE html>
<html>
<body>
<div id = "result"> </div>
<script>
try{
   let sum=a+2;
   document.getElementById("result").innerHTML = sum;
}
catch(e){
    document.getElementById("result").innerHTML = e;
}
</script>
</body>
</html>

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 this example we will make use of the onerror event in the code that we mentioned above section to catch the ReferenceError object. Here is the complete code that will do the task:

<!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 Stack: " + error;
            document.getElementById("result").innerHTML = msg;
        };
        let sum = a + 2;
    </script>
</body>
</html>

Conclusion

In this article, we learned about RefernceError and onerror events in JavaScript. We also saw that with the help of the onerror event we can capture the ReferenceError object.

Updated on: 12-Sep-2023

30 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements