Ajax Error Handling Mechanism

Source: Internet
Author: User
Tags response code unsupported

The core component of the Ajax framework is the XMLHttpRequest JavaScript Object, which allows client developers to send and receive XML documents through HTTP without interrupting user operations or hiding pages. Now, some may be afraid because it suddenly allows client developers who may use too many verification forms and animated images to deliver XML documents and process HTTP header information. However, without risks, there is no benefit. We don't need to be afraid. I will demonstrate how to use XMLHttpRequest to add some previously impossible and unfeasible features. It also reduces errors and improves product quality.

XMLHttpRequest and xml dom in Javascript

First, we need to establish some rules. Special XMLHttpRequest objects and general xml dom are widely supported by the latest browsers (ie, Mozilla, Safari, and opera), although in general, microsoft will add something for its own implementation and require some special processing. Although more of our friends directly implement XMLHttpRequest, ie still requires you to instantiate an activexobject with the same attributes. You can find related overview and a list of all features on the Apple developer link site. The following is a basic example:

VaR req;

Function postxml (xmldoc ){

If (window. XMLHttpRequest) Req = new XMLHttpRequest ();

Else if (window. activexobject) Req = new activexobject ("Microsoft. XMLHTTP ");

Else return; // failed

Req. Open (method, serveruri );

Req. setRequestHeader ('content-type', 'text/xml ');

Req. onreadystatechange = xmlposted;

Req. Send (xmldoc );

}

Function xmlposted (){

If (req. readystate! = 4) return;

If (req. Status = 200 ){

VaR result = Req. responsexml;

} Else {

// Failed

}

}

There are many potential users of this powerful feature, and the exploration of its functions is just beginning. But before you try to build XML functions on the web, I suggest you set up a "security net" to ensure that your ambitions (IDEAS) will not be compromised.

Javascript error handling Basics

Javascript has been around for a long time. Its early versions are primitive and lack features. They are just implementations. The latest browser not only supports the try/catch/finally keyword in C ++ and Java, but also implements the onerror event, which can capture any errors during the runtime. Its usage is very direct:

Function riskybusiness (){

Try {

Riskyoperation1 ();

Riskyoperation2 ();

} Catch (e ){

// E is an error object with at least two attributes: name and message

} Finally {

// Clear the message

}

}

Window. onerror = handleerror; // capture the security net of all errors

Function handleerror (message, Uri, line ){

// Prompt the user that the page may not respond normally

Return true; // stop the default message

}

Actual Example: Pass client errors to the server

Now we know some basic knowledge about XMLHttpRequest and JavaScript error handling. Let's take a look at an example of using both. You may think JavaScript errors can be easily displayed in the popular "Yellow death triangle, but there are still some errors passed to the Quality Department of Public Web sites of several basket-raising companies.

Therefore, I will provide a method to capture errors and record errors to the server, so that others may fix these problems. First, consider the client. The client must provide a class that is used as a logger object and can process various details transparently.

The following is the constructor we have created:

// Class Constructor

Function logger (){

// Field

This. req;

// Method

This. errortoxml = errortoxml;

This. log = log;

}

Next, we define a method that serializes the error object into XML. By default, the error object has only two types of attributes: name and message. However, the third attribute (location) is used, which is sometimes useful.

// Map errors to XML documents

Function errortoxml (ERR ){

VaR xml = '<? XML version = "1.0"?> \ N' +

'<Error> \ n' +

'<Name>' + err. Name + '</Name> \ n' +

'<Message>' + err. Message + '</message> \ n ';

If (ERR. Location) XML + = '<location>' + err. Location + '</location> ';

XML + = '</error> ';

Return XML;

}

The log method is followed. This is the most basic part of the script. It truly implements the above principles. Note that the POST method is used in the call. Essentially, what I create here is a custom web service that is read-only and creates a new record for each successful request. Therefore, post is the only proper choice.

// LOG method

Function log (ERR ){

// View features

If (window. XMLHttpRequest) This. Req = new XMLHttpRequest ();

Else if (window. activexobject) This. Req = new activexobject ("Microsoft. XMLHTTP ");

Else return; // failed

// Set the method and Uri

This. Req. Open ("Post", "/cgi-bin/ajaxlogger. cgi ");

// Set request header information. Referer is the top-level URI if it occurs in an included. js file.

// Its location may be different from the wrong location

This. Req. setRequestHeader ('Referer', location. href );

This. Req. setRequestHeader ('content-type', 'text/xml ');

// The function called when the request is complete

This. Req. onreadystatechange = errorlogged;

This. Req. Send (this. errortoxml (ERR ));

// If the request is not completed within 10 seconds, some error messages will appear.

This. Timeout = Window. setTimeout ("abortlog ();", 10000 );

}

The last part of the class creates a logger class instance. This class should have only one instance.

// Only one logger instance exists

VaR logger = new logger ();

The last two functions are only used for trivial transaction management. If a problem occurs during record errors, we can hardly perform task transactions except for interfering with users. However, this situation will never happen. These are not class methods, because the event does not point to the pointer of our object, but it will point to the created logger instance.

// We tried it, but the connection is incorrect and there is no hope

Function abortlog (){

Logger. Req. Abort ();

Alert ("attempt to log the error timed out .");

}

// Called when the Request status changes

Function errorlogged (){

If (logger. Req. readystate! = 4) return;

Window. cleartimeout (logger. Timeout );

// The request is complete.

If (logger. Req. Status >=400)

Alert ('attempt to log the error failed .');

}

all the preceding codes are packaged into one. JS file. We can include this file on any (or every) page of the site. The following is an example of how to include this file:

Now you know how to integrate a logger into an HTML page. The rest of the work is to define a method to receive and convert messages. I chose to use the underlying generic naming method and created a CGI script in Perl. This script uses some modules I like. It uses XML: simple to analyze post data, use CGI: carp to import the result directly to the httpd error log, which saves the system administrator time because he does not need to view another log. This script also contains many good examples, which properly record different success and failure conditions.

Use CGI;

Use CGI: carp QW (set_progname );

Use XML: simple;

My $ request = CGI-> New ();

My $ method = $ request-> request_method ();

# The method must be post

If ($ method EQ 'post '){

Eval {

My $ content_type = $ request-> content_type ();

If ($ content_type EQ 'text/xml '){

Print $ request-> header (-status => '2017 unsupported media type',-type => 'text/xml ');

Croak "invalid content type: $ content_type \ n ";

}

# If the method is post, the content is neither URL encoding nor multi-part form,

# Then the entire post will be filled in a parameter: postdata.

My $ error_xml = $ request-> param ('postdata ');

My $ ref = xml: simple: xmlin ($ error_xml );

My ($ name, $ MSG, $ location) = ($ ref-> {'name'}, $ ref-> {'message '},'');

$ Location = $ ref-> {'location'} If (defined ($ ref-> {'location '}));

# Change the log name

Set_progname ('client-side error ');

My $ remote_host = $ request-> remote_host ();

Carp "Name: [$ name], MSG: [$ MSG], Location: [$ location]";

};

If ($ @){

Print $ request-> header (-status => '1970 internal server error',-type => 'text/xml ');

Croak "error while logging: $ @";

} Else {

# This part of the response code indicates that the operation was successful, but the client should not expect any content

Print $ request-> header (-status => '2017 no content',-type => 'text/xml ');

}

} Else {

Print $ request-> header (-status => '2017 method not ororted',-type => 'text/xml ');

Croak "unsupported method: $ method ";

}

Finished! Now, when some obscure JavaScript enters the system, you can expect your log monitor to start to flash with a red light, and your client developers will receive a call late at night.

Related Article

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.