Discussion on the error handling mechanism of AJAX (2)

Source: Internet
Author: User
Tags define object error handling header html page include unsupported window
Ajax| Error | Error handling Practical Example: Passing client errors to the server

Now that we know some of the basics of XMLHttpRequest and JavaScript error handling, let's look at an implementation example that uses both. You may think that JavaScript errors can be easily displayed in the popular "Yellow Death triangle", but there are still some errors passed to the quality Department of the public Web sites of several basket-stock companies.

Therefore, I will provide a way to catch errors and log errors to the server so that others can fix these problems. First, we consider the client. The client must provide a class that is used as a logger (Logger) object to transparently handle various details.

Here is the constructor we established:

Constructors for classes
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 properties, namely, name and message, but we still use the third property (location), which is sometimes useful.

mapping errors to XML documents
function Errortoxml (err) {
var xml = ' \n ' +
'\ n ' +
'' + err.name + '\ n ' +
'' + err.message + '\ n ';
if (err.location) XML = '' + err.location + '';
XML + = '';
return XML;
}

Then the log method. This is the most basic part of the script, and it really implements the principle above. Notice that we are using the Post method in the call. Essentially, what I'm building here is a custom Web service that is read-only and creates new records for each successful request. Therefore, post is the only appropriate choice.

Log method of logging class
function log (err) {
View Attributes
if (window. XMLHttpRequest) This.req = new XMLHttpRequest ();
else if (window. ActiveXObject) this.req =new activexobject ("Microsoft.XMLHTTP");
else return; Failed.
Set method and Uri
This.req.open ("POST", "/cgi-bin/ajaxlogger.cgi");
Sets the request header information. REFERER is the top-level URI, if it occurs in a contained. js file
Then its location may be different from the wrong location.
This.req.setRequestHeader (' REFERER ', location.href);
This.req.setRequestHeader (' Content-type ', ' text/xml ');
The function that is called when the request completes
This.req.onreadystatechange = errorlogged;
This.req.send (This.errortoxml (err));
If the request does not complete within 10 seconds, there are some error messages
This.timeout = Window.settimeout ("Abortlog ();", 10000);
}

The last part of the class establishes an logger class instance. This class should have only one instance.

Only one Logger instance
var logger = new Logger ();

The last two functions are for trivial transaction management only. If there is a problem recording errors, we can hardly do task transactions other than interfering with the user. However, this situation will never occur. These are not methods of the class, because the event does not have a pointer to our object, but it points to the logger instance we set up.

We tried, but the connection was wrong, there was no hope.
function Abortlog () {
Logger.req.abort ();
Alert ("Attempt to log the error timed out.");
}

Call when the state of the request has changed
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 of the preceding code is packaged into a. js file that we can include in any (or every) page of the site. Here is an example of how to include this file:



Now that you know how to integrate a logger into an HTML page, the rest of the work is to define a way to receive and convert messages. I chose to use the lowest common naming method, creating a CGI script in Perl that used some of my favorite modules, using Xml::simple to analyze post data, and using Cgi::carp to import the results directly into the httpd error log. This saves the system administrator's time because he doesn't need to see another log. The script also contains a number of good examples that properly document 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 ();
# 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 => ' 415 unsupported Media Type ',-type => ' text/xml ');
Croak "Invalid content Type: $content _type\n";
}
# If the method is post, the content is neither URL-coded nor multiple-part form,
#Then the entire post will be filled into one 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 name in the log
Set_progname (' client-side error ');
My $remote _host = $request->remote_host ();
Carp "Name: [$name], msg: [$msg], location: [$location]";
};
if ($@) {
Print $request->header (-status => ' 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 => ' 204 No content ',-type => ' text/xml ');
}
} else {
Print $request->header (-status => ' 405 Method not supported ',-type => ' text/xml ');
Croak "Unsupported method: $method";
}

It's done! Now, when some incomprehensible JavaScript enters the system, you can expect your own log monitor to start flashing red, and your client developer gets the call late at night.
    • Ajax: A new way to build Web apps
    • Discussion on the error handling mechanism of AJAX (1)
    • A brief analysis of Ajax development Technology in Rails system (2)
    • A brief analysis of Ajax development Technology in Rails system (1)


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.