O'Reilly logo

Learning PHP, MySQL, and JavaScript by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using onError

Here are more constructs not available in PHP. Using either the onError event, or a combination of the try and catch keywords, you can catch JavaScript errors and deal with them yourself.

Events are actions that can be detected by JavaScript. Every element on a web page has certain events that can trigger JavaScript functions. For example, the onClick event of a button element can be set to call a function and make it run whenever a user clicks on the button.

Example 15-11 illustrates how to use the onError event.

Example 15-11. A script employing the onError event
<script>
onerror = errorHandler
document.writ("Welcome to this website") // Deliberate error

function errorHandler(message, url, line)
{
    out  = "Sorry, an error was encountered.\n\n";
    out += "Error: " + message + "\n";
    out += "URL: "   + url + "\n";
    out += "Line: "  + line + "\n\n";
    out += "Click OK to continue.\n\n";
    alert(out);
    return true;
}
</script>

The first line of this script tells the error event to use the new errorHandler function from now on. This function takes three parameters, a message, a url and a line number, so it’s a simple matter to display all these in an alert pop up.

Then, to test the new function, a syntax error is deliberately placed in the code with a call to document.writ instead of document.write (the final e is missing). Figure 15-1 shows the result of running this script in a browser. Using onError this way can also be quite useful during the debugging process.

Figure 15-1. Using the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required