How to catch all JavaScript errors?

JavascriptWeb DevelopmentFront End Technology

To catch all JavaScript errors, use onerror() method. The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.

The onerror event handler provides three pieces of information to identify the exact nature of the error −

  • Error message − The same message that the browser would display for the given error
  • URL − The file in which the error occurred
  • Line number− The line number in the given URL that caused the error

Example

 Live Demo

You can try to run the following code to catch JavaScript errors −

<html>
   <head>
      <script>
         <!--
            window.onerror = function (msg, url, line) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following to see the result:</p>

      <form>
         <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>
   </body>
</html>

Output

raja
Published on 23-Feb-2018 11:20:45
Advertisements