Exception Handling in JavaScript: Catching User Input - Catching user data: triggering errors through web forms
(Page 3 of 4 )
Since web forms are the most common mechanism for collecting user data, there is the certain possibility of multiple errors occurring when program control is transferred to users. It is because of this simple but extremely relevant concept that form validation becomes a critical point within application development.
Bearing in mind that forms are potentially dangerous, and considering that bad user data can quickly break up an application if wrong assumptions are made, the next thing to do is to build an example that clearly exemplifies the way a simple web form can be used for triggering different errors, and accordingly implementing the appropriate handlers.
Thus, the first example comprises two sections. First, the “showError()” function, which looks like this:
function showError(){
try {
var data=document.getElementsByTagName('form')[0].elements['data'].value;
eval(data);
}
// catch exceptions
catch(e){
var p=document.createElement('p');
p.appendChild(document.createTextNode('An exception was
thrown by the script. Error name :'+e.name+' Error
message :'+e.message));
document.body.appendChild(p);
}
}
// call function when page is loaded
window.onload=function(){
var W3C=document.getElementById&&document.
getElementsByTagName&&document.createElement;
if(W3C){
document.getElementsByTagName('input')[1].onclick=showError;
}
}
And second, the simple web form for entering data:
<form method="post">
<input type="text" name="data" />
<input type="button" value="Evaluate Code!" />
</form>
As you can appreciate, the above example implements a straightforward method for trapping errors that occur when bad data is entered. The “showError()” function wraps up the code responsible for evaluating user input into a “try” block, as depicted below:
try {
var data=document.getElementsByTagName('form')[0].elements
['data'].value;
eval(data);
}
What the above snippet does is simply execute any string entered on the web form as JavaScript code, through the “eval()” function. Also, I’ve attached an “onclick” event handler to the form button, so the data can be tested without actually submitting the form, but you can easily modify this by introducing another event handler.
As you’ve learned previously, the “catch” block takes care of catching all raised errors when conflicting data is entered, allowing the display of the script’s output directly on the browser. Of course, real examples are always required, so let’s enter erroneous data through the provided form and see how the generic error handler catches several exceptions.
First, let’s force a syntax error by entering the following code:
varb =
In response to this error (variable declaration is incomplete), the script traps a primary syntax error, by displaying the following message:
An exception was thrown by the script. Error name :SyntaxError Error message :syntax error
As with the first case, it’s possible to trigger a range error, by entering something like this:
var a=new Array(1111222223333444456789)
Obediently, the script displays the following message:
An exception was thrown by the script. Error name :RangeError Error message :invalid array length
In a similar way, a reference error can be deliberately raised, by using a non-existent variable:
alert(a)
The above expression raises a reference error, which is trapped and displayed as follows:
An exception was thrown by the script. Error name :ReferenceError Error message :a is not defined
The final case illustrates how a type error is trapped, by using the following line of code:
var a=1;alert(a[1].length);
For the above example, the script displays the appropriate message:
An exception was thrown by the script. Error name :TypeError Error message :a[1] has no properties
Definitely, there are numerous possibilities to explore by entering different fragments of code and studying the corresponding responses triggered by the generic error handler. It’s just a matter of testing each possible form entry.
Given the previous script, it’s fairly easy to adapt the code for working with input controls other than forms. Thus, in the next few lines, I’ll redefine the “showError()” function for use with built-in JavaScript prompts.
Next: A quick and dirty error handler: using JavaScript prompts >>
More JavaScript Articles
More By Alejandro Gervasio