Javascript Tutorial: Handling All Errors

I found a very interesting method to handle errors on JavaScript. What this does is to handle all error occurs in the script to a single function so whenever any error occurs, it will go into this particular function and alert the user.

JavaScript

function handleError()
{
alert(An error has occurred!');
return true;
}
window.onerror = handleError;

What it does is that whenever a run time error occurs, the function will goes into action! For example you try to trigger a function that does not exist! Instead of making your program stop functioning, we can provide a error message using the above method which can promote a more user friendly environment whenever an error occurs on our script. This is neat stuff!

One thought on “Javascript Tutorial: Handling All Errors

  1. nice trick, thank you ! a minor change to report the error description :

    function handleError(e)
    {
    alert('An error has occurred!\n'+e);
    return true;
    }
    window.onerror = handleError;

Comments are closed.