Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

JavaScript window.onerror event

Suggested Videos
Part 29 - JavaScript arguments object
Part 30 - Recursive function in JavaScript
Part 31 - Error handling in JavaScript



In general we use try/catch statement to catch errors in JavaScript. If an error is raised by a statement that is not inside a try...catch block, the onerror event is fired.



Assign a function to window.onerror event that you want to be executed when an error is raised as shown below. The function that is associated as the event handler for the onerror event has three parameters:

message Specifies the error message
URL Specifies the location of the file where the error occurred
line Specifies the line number where the error occurred

JavaScript window onerror event example
window.onerror = function (message, url, line)
{
    alert("Message : " + message + "\nURL : " + url + "\nLine Number : " + line);
    // Return true to supress the browser error messages
    // (like in older versions of Internet Explorer)
    return true;
}
NonExistingFunction();
Output : 
JavaScript window onerror event example

If the error is handled by a try/catch statement, then the onerror event is not raised. onerror event is raised only when there is an unhandled exception.
window.onerror = function (message, url, line)
{
    alert("Message : " + message + "\nURL : " + url + "\nLine Number : " + line);
    return true;
}

try
{
    NonExistingFunction();
}
catch (e)
{
    document.write(e.message);
}
Output : 'NonExistingFunction' is undefined 

onerror event handler method can also be used with HTML elements : In the example below, since the image is not existing and cannot be found we get "There is a problem loading the image" error.
<script type="text/javascript">
    function imageErrorHandler()
    {
        alert("There is a problem loading the image");
    }
</script>
<img src="NonExistingImage.jpg" onerror="imageErrorHandler()" />

Output : 
onerror event handler in javascript

JavaScript tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources