Exception Handling in JavaScript: Catching User Input - A quick and dirty error handler: using JavaScript prompts
(Page 4 of 4 )
Once you’ve learned how to generate most of the primary error types through regular web forms, it’s extremely easy to rewrite the above described “showError()” function, in order to test potential errors. Of course, I won’t bore you again with annoying error messages. Instead, I’ll list the rewritten function, so you can tweak it and see what happens. Having said that, here’s the pertinent function, this time using a dirty prompt method:
function showError(){
try {
var data=prompt('Enter code for being evaluated');
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){
showError();
}
}
As you can see, the function remains nearly the same. The only change worth noting here is the use of a JavaScript prompt() method for entering erroneous (or correct) data and triggering some types of errors. Consider this method as a quick and dirty -- but didactical -- mechanism for implementing an exception handler, if you’re not inclined to test JavaScript code through a web form. In either case, results will closely resemble the ones obtained with forms.
Wrapping up
At this point, hopefully you’ve started playing around with JavaScript exceptions, in order to make code that is a lot more robust and efficient. Over this part of the series, I’ve provided you with enough examples to demonstrate how errors can be triggered by using some of the most common data collectors, such as web forms and JavaScript prompts.
However, even when core concepts and basic examples have been fully covered, a “real world” application of exception handlers is preferred. Bearing this in mind, the next part of the series will be focused entirely on implementing exceptions in an old favorite: form validation. How this is done will be the next topic to be explained over the next tutorial. Don’t miss it!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |