Help

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Partners
This is a

Retrieving additional information about a JavaScript error through scripting

While you may very well be content with simply using the onerror event to suppress JavaScript errors, its important to understand just what happens when the onerror event fires, and use that to create more complicated onerror functions.

Whenever the onerror event fires, JavaScript logs all information regarding the error and provides you with a mean to access it. The info I'm referring to is the same info shown inside the default browser error dialog whenever a js error occurs. First off, lets examine what the default error box of your browser tells you in the event of an error. The information inside usually looks something like this:

JavaScript Error: http://javascriptkit.com/test.htm, line 8:
missing ) after argument list.
document.write('hi there'
..........................^

The default error box always informs the surfer the url of the page containing the error, the line where the error occurred, and a (less than helpful, I might add) message attempting to explain why the error occurred. Using JavaScript, we have access to the same information provided by the default box, realized through optional parameters you can specify inside the function to be executed when the onerror event fires. (Don't worry, all this will become clear very soon):

Parameter function
1st parameter Contains the message explaining why the error occurred.
2nd parameter Contains the url of the page with the error script
3rd parameter Contains the line number where the error occurred

Lets clear the mist and modify our original error code of the previous page so that it alerts us information regarding the error:

<head>
<script type="text/javascript">
function tellerror(msg, url, linenumber){
alert('Error message= '+msg+'\nURL= '+url+'\nLine Number= '+linenumber)
return true
}
window.onerror=tellerror
</script>

<script>
document.write('hi there'
</script>
</head>

Click here to see an actual demo.

The key to the above are the three parameters inside function tellerror(). When defined, JavaScript uses them to store the error information. The parameters can be any name.