Categories
Javascript

JavaScript onerror() method to handle error

The JavaScript onerror method is the first thing to handle error in JavaScript. This error event is called on the window object whenever any exception occurs on the page.

There are three pieces of information to identify the exact error:

  • Error message
  • URL, in which file the error occurred
  • The line number in the given URL where error occurred
You may like:  AngularJS Controller

Example of JavaScript onerror:

<html>
<head>
<script type="text/javascript">
window.onerror = function (msg, url, line) {
console.log("Message : " + msg );
console.log("url : " + url );
console.log("Line number : " + line );
}
</script>
</head>
<body>
<p>Click the following button:</p>
<form>
<input type="button" value="Click Here" onclick="myClick();" />
</form>
</body>
</html>

Read Also: JavaScript Strict mode

Alternatively, you can use an onerror method to display an error message if there is any problem in loading an image.

<img src="image.jpg" onerror="alert('Loading failed')" />
Avatar for Jacob Frazier

By Jacob Frazier

Based on United States, Jacob Frazier is a skilled JavaScript developer with over 8 years of experience. He is passionate about change and trying new things, both professionally and personally. He loves startups and is extremely proactive.

Leave a Reply

Your email address will not be published. Required fields are marked *