JavaScript onerror() method to handle error

associate functions with objects

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

Example of JavaScript onerror:

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

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')" />

Leave a Reply

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