Using onerror

Let’s look at a few 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 14-11 illustrates how to use the onerror event.

Example 14-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 in the future. This function takes three parameters—a message, a url, and a line number—and 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 14-1 shows the result of running this script in a browser. Using onerror this way can also be quite useful during the debugging process. ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition 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.