Getting additional details on an error
While you may very well be content with simply using the
onerror
event to suppress JavaScript errors, this event
provides additional details on the error that just occurred should you want
them, by way of 3 parameters that get indirectly passed into the function on
the right. By default when an JavaScript error occurs on the page, the
browser informs the user 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:
When you utilize the onerror
event to intercept
JavaScript errors on the page, you have access to these 3 pieces of
information as well. The trick is to make room for 3
parameters (can be named anything) in the function assigned to
window.onerror
. Using our trusted example from the previous pages again,
here's how to modify it to gain access to details about the error:
<head>
<script type="text/javascript">
window.onerror=function(msg, url, linenumber){
alert('Error message: '+msg+'\nURL: '+url+'\nLine
Number: '+linenumber)
return true
}
</script>
<script type="text/javascript">
document.write('hi there'
</script>
</head>
Click here to see a live demo. The 3 parameters provide the following nuggets of information:
Parameter (in order) | Description |
Error Message | Contains a message explaining why the error occurred. |
Error URL | Contains the url of the page with the error script |
Error Line Number | Contains the line number where the error occurred |
- Tutorial introduction
- Using the onerror event to suppress JavaScript errors
- Getting additional details on an error
- Creating custom JavaScript error dialog boxes