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 ...

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.