Web tip: Properly handle errors in JavaScript

Source: Internet
Author: User
Tags define object error handling finally block reference return
javascript| Error | tips | Web page

No matter how technical you are, errors or anomalies are part of the life of the application developer. The discontinuity of web development leaves many places where errors can occur and that do occur. The key to the solution is to handle any unforeseen (or foreseeable) error to control the user's experience. With JavaScript, there are a variety of technical and linguistic features that can be used to correctly solve any problem.

Check everything

It's a good programming practice to check everything before you start, which means you should check the validity of objects, method calls, and so on before using them. This avoids the error associated with instantiating an object or invoking a method that does not exist. List A checks for objects (variables and fields) before they are used. The script guarantees that they are valid or Non-null fields before using the Field objects.

List A

<title>js test</title>
<script type= "Text/javascript" >
function Validate () {
var doc = document.forms[0];
var flag = true;
if (Doc!= null) {
if (doc.fullname!= null) {
if (Doc.fullName.value = = "") {
Flag = false;
}
} else {
Flag = false;
}
if (doc.contactnumber!= null) {
if (Doc.contactNumber.value = = "") {
Flag = false;
}
} else {
Flag = false;
}
if (flag) {
Alert (' Validation successful, document would be submitted. ');
Doc.submit ();
} else {
Alert (' Enter values before submitting. ');
} }
return 0; }
</script>
<body>
<form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form>
</body>

You do not need to actually check for validity-you can simply use an object in an if statement, and if it is not an invalid object, the value is true. This syntax is used in List B, and the getElementById method is also used. It uses an if statement to ensure that the getElementById method is supported (exists) before continuing.

List B

<title>js test</title>
<script type= "Text/javascript" >
function Validate () {
var doc = document.forms[0];
var flag = true;
if (Doc!= null) {
if (Doc.getelementbyid) {
if (Doc.getelementbyid ("FullName")) {
if (Doc.fullName.value = = "") {
Flag = false;
}
} else {
Flag = false;
}
if (Doc.getelementbyid ("Contactnumber")) {
if (Doc.contactNumber.value = = "") {
Flag = false;
}
} else {
Flag = false;
}
if (flag) {
Alert (' Validation successful, document would be submitted. ');
Doc.submit ()
} else {
Alert (' Enter values before submitting. ');
} }
return 0; }
</script>
<body>
<form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form>
</body>

Although it is a good way to check them before using them, there are times when errors occur. In these instances, the JavaScript language makes it easy to find errors that can continue.

Error found

Similar to other languages such as Java and C #, JavaScript includes try/catch/finally statements. A try statement contains a set of code in which exceptions such as run-time errors can occur. The catch clause outlines how errors are handled, and finally blocks include code that is always executed.

In general, the code manages to execute a set of code that, if not executed successfully, passes to the catch block. If no errors occur, the catch block is skipped. Finally blocks are executed after the try and catch blocks have finished. Its syntax is as follows:

Try
{
Code
}
Catch
{
Code
}
Finally
{
Code
}

Catch and finally blocks are optional, but it is meaningless if there are no catch blocks. Carefully consider list C, which demonstrates the use of try/catch/finally. The error occurs when the referenced field does not exist in the table.

List C

<title>js test</title>
<script type= "Text/javascript" >
function DoIt () {
if (Document.forms[0].firstname.value = = "") {
Do something
}
return 0; }
</script>
<body>
<form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form>
</body>

A try/catch block cannot avoid errors, but it can handle errors gracefully so that users do not face obscure browser error messages. Watch List D.

List D

<title>js test</title>
<script type= "Text/javascript" >
function DoIt () {
try {
if (Document.forms[0].firstname.value = = "") {
Do something
}
catch (e) {
document.write ("An unexpected error has occurred.<br><br>");
document.write ("Please contact the administrator.<br><br>");
document.write (E.message);
finally {
Document.forms[0].submit ();
}
return 0; }
</script><body>
<form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

It prompts for the following information, but the finally block guarantees the form's submission-no matter what the error occurs.

An unexpected error has occurred.
Please contact the administrator.
' Document.forms.0.firstname.value ' is null or isn't an object

A single catch block can handle all problems, but multiple catch statements can be used to handle a particular error. This question will be covered in the next section.

Try/catch statements make it easy to handle unforeseen errors. In some cases, you may want to handle errors in a different way, JavaScript provides a throw statement. Its syntax is very basic--throw followed by the exception that is to occur. This allows you to define and raise custom exceptions. The code in List E creates an exception with a missing value, and it is generated.

List E

<title>js test</title>
<script type= "Text/javascript" >
function Missingvalueexception (errmsg) {
This.message = errmsg;
This.name= "Missingvalueexception";
}
function DoIt () {
try {
if (Document.forms[0].fullname.value = = "") {
Nonameexception = new Missingvalueexception ("The name is missing.");
Throw nonameexception;
} else {
Document.forms[0].submit ();
}
catch (e) {
document.write ("An unexpected error has occurred.<br>");
document.write ("Please contact the administrator.<br>");
document.write (E.message);
finally {
Document.forms[0].submit ();
}
return 0; }
</script><form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

It will display the following information (if no value is entered in the field):

An unexpected error has occurred.
Please contact the administrator.
The name is missing.

In addition, you can use operator instanceof to determine the type of exception to react. The code in list F checks the type of the exception object and displays the data accordingly.

List F

<title>js test</title>
<script type= "Text/javascript" >
function Missingvalueexception (errmsg) {
This.message = errmsg;
This.name= "Missingvalueexception";
}
function DoIt () {
try {
if (Document.forms[0].fullname.value = = "") {
Nonameexception = new Missingvalueexception ("The name is missing.");
Throw nonameexception;
}
catch (e) {
if (e instanceofmissingvalueexception) {
document.write (e.message + "<br>");
document.write ("Please contact the administrator.<br><br>");
} else {
document.write ("An unexpected error has occurred.<br>");
document.write ("Please contact the administrator.<br>");
document.write (E.message);
}} finally {
Document.forms[0].submit ();
return 0; }
</script><form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

Operator instanceof can be used in conjunction with standard errors. JavaScript defines the following standard JavaScript error types:

Evalerror: Indicates that the global eval function is using an error.
Rangeerror: Indicates that a value exceeds the range of allowable values.
Referenceerror: An illegal reference was found.
SyntaxError: A syntactic parsing error has occurred.
TypeError: The actual type of an operand differs from the expected type.
Urierror: One of the global URI functions (encoding URI or decoding URI) uses an error.
The code in List G takes the TypeError type in a catch statement. A typographical error (ddocument) occurred because one more D was in the line referencing the field name (document).

List g

<title>js test</title>
<script type= "Text/javascript" >
function Missingvalueexception (errmsg) {
This.message = errmsg;
This.name= "Missingvalueexception";
}
function DoIt () {
try {
if (Ddocument.forms[0].fullname.value = = "") {
Nonameexception = new Missingvalueexception ("The name is missing.");
Throw nonameexception;
}
catch (e) {
if (e instanceoftypeerror) {
document.write ("Reference error while accessing the Name field.<br><br>");
document.write ("Please contact the administrator.<br><br>");
document.write (E.message);
} else {
document.write ("An unexpected error has occurred.<br><br>");
document.write ("Please contact the administrator.<br><br>");
document.write (E.message);
}} finally {
Document.forms[0].submit ();
return 0; }
</script><body><form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

Handle all Page faults

Another feature that you can control yourself is the Window.onerror event. As with all other JavaScript events, you can define a function or a code that runs when an event is triggered. It can be used to handle or ignore errors. The page in List h shows simple information about all of the JavaScript errors encountered. Because the specified function does not exist, the error occurs when the button is clicked. List I is using the OnError event to ignore all errors.

List h

<title>onerror test</title>
<script type= "Text/javascript" >
function Handleerrors () {
Alert ("A JavaScript error has occurred.");
return true;
}
Window.onerror = handleerrors;
</script><body>
<form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

List I

<title>js test</title>
<script type= "Text/javascript" >
function Ignoreerrors () {
return true;
}
Window.onerror = ignoreerrors;
</script><body><form id= "Frmtest" >
Name: <input id= "FullName" name= "FullName" type= "text" ><br>
Address: <input id= "Contactnumber" name= "Contactnumber" type= "text" ><br>
<input type= "button" value= "Submit" >
</form></body>

One problem with the OnError event is browser support. The biggest problem is in the Opera browser, so you should make sure that all of your target browsers support this feature before you combine your browser and your application.

Handle carefully

Errors are part of every application, but proper error handling is not. The proper use of JavaScript's error handling features and automatic and flexible decoding can make the user's experience smoother and make diagnostics easier for the developer.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.