Error analysis and Ajax (XMLHttpRequest)

Source: Internet
Author: User
Tags add object error handling header implement net unsupported window
Ajax|request|xml|xmlhttprequest| Error Even if you haven't heard it yet, Ajax has become the hottest word in web technology (as mentioned in an article on adaptive path). The key to an AJAX framework is a JavaScript object called XMLHttpRequest, through which client developers can send and receive XML documents directly through HTTP without interrupting user action or by using the full use of hidden forms. Now, some people may have this concern, and it's okay to have client developers who used to make form checksums and add picture animations suddenly take responsibility for parsing the XML document structure and dealing with the header part of the HTTP protocol? But there is no risk and there is no return. To mitigate this confusion, I'll show you how to use XMLHttpRequest to implement functionality that wasn't previously implemented, and how to reduce program errors and improve program quality.

JavaScript Basics for XMLHttpRequest and XML DOM

First, we need to declare some rules. The most commonly used browsers (IE, Mozilla, Safari, Opera) provide support for XMLHttpRequest objects, as well as a wide range of support for XML DOM, Although as usual: Microsoft (Microsoft) uses a slightly different implementation and some places that require special attention. And our more aggressive friends directly implement XMLHttpRequest different, IE requires you to create an instance of a ActiveXObject object with the same attributes. The Apple Developer Connection website has a very good article that outlines the XMLHttpRequest and enumerates its full features.

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;
Fall on We (method, Serveruri);
Req.setrequestheader (' Content-type ', ' text/xml ');
Req.onreadystatechange = Xmlposted;req.send (xmldoc);
}function xmlposted () {if (req.readystate!= 4) return;
if (Req.status = =) {var result = Req.responsexml;
else {//Fall on Sword}}

This powerful tool has a wide range of applications and is only beginning to explore its potential applications. But before anyone who is ready to build an XML garden online is out of control, I suggest we set up a safety net to prevent anyone with high ambitions from breaking their necks.

JavaScript error Handling Basics

JavaScript supports simple error handling in its earlier versions, but it's very rudimentary, with only a few features and poorly implemented. Recent browsers not only support keyword try/catch/finally similar to C + + and Java for error handling, but also implement onerror events to provide capture of any errors that occur during runtime. The method is simple and straightforward:

function riskybusiness () {try {riskyOperation1 ();
RiskyOperation2 ();
catch (E) {/E is an error type object//At least two attributes: name and message} finally {//cleanup work}}window.onerror = HandleError;
The Security net function handleerror (message, URI, line) {//Prompts the user to catch the error, the page may not respond correctly to return true;
This will terminate the default information}

One instance: Passing a client's error to a server

Now that we've learned the basics of XMLHttpRequest and JavaScript error handling, let's take a simple example to see how to use these two links together. You might think that JavaScript bugs should be easy to recognize in the yellow triangle of the status bar, but I still find them in the public-facing websites of several reliable organizations that have escaped the quality assessment department.

So here I'm going to provide a catch error and log them on the server, hoping to remind someone to modify these errors. First, we consider the client. The client needs to provide a class that generates logging, which must be instantiated only once in use and transparently handle the complex details.

We first create the constructor:

A class constructor method function Logger () {//domain this.req;
Method this.errortoxml = Errortoxml;
This.log = log;}

Second, we define a way to convert an Error object to XML. By default, the Error object has only two properties: Name and message, but we need to check the third potentially useful attribute location.

Mapping an error to XML document function Errortoxml (err) {var xml = ' <?xml version= ' 1.0 '? >\n ' + ' <error>\n ' + ' <name> ' + + ' </name>\n ' + ' <message> ' + err.message + ' </message>\n '; if (err.location) XML + = ' <locati On> ' + err.location + ' </location> '; XML + + ' </error> '; return XML;}

Then the log method. This is the most basic part of the script that combines the two principles above (XMLHttpRequest and XML DOM). Note that we use the Post method. In this I essentially created a write-only custom Web service that would create new records on every successful request. Therefore, using post is the only feasible method.

The journaling method of the Logger class function log (ERR) {//Sniffer environment if window. XMLHttpRequest) This.req = new XMLHttpRequest (); Else if (window. ActiveXObject) this.req =new activexobject ("Microsoft.XMLHTTP");
else return; REACTIVE return//Determination and ("POST", "/cgi-bin/ajaxlogger.cgi");
Set the headers of the request. If the error occurs in a contained. js file,//referer This topmost URI may be inconsistent with the place where the error occurred this.req.setRequestHeader (' REFERER ', location.href);
This.req.setRequestHeader (' Content-type ', ' text/xml ');
The function to call when the request is completed this.req.onreadystatechange = errorlogged;
This.req.send (This.errortoxml (err));
If the request cannot be completed in 10 seconds,//Required Transaction This.timeout = Window.settimeout ("Abortlog ();", 10000);}

Finally, instantiate the logging class. Note that this class can have only one instance.
Logger can only have one instance of var logger = new Logger ();

Finally there are two methods that are called in our class. If there is an error in logging the error, there is no other way than telling the user. If you're lucky, that's not going to happen. Because the browser event does not have a reference to our object, but references the logger instance we created, the two methods are not methods of logging classes.

Although you have tried, but if there is a connection error, give up the function Abortlog () {logger.req.abort ();
Alert ("Attempt to log the error timed out.");} Call Function errorlogged () {if (logger.req.readyState!= 4) return;window.cleartimeout (logger.timeout) When request status is changed ;
Request completed if (Logger.req.status >=) alert (' Attempt to log the error failed. ')

All of the above code can be written in a. js file that you can introduce into any (or all) page. Here's an example showing how to introduce and use this file:

<script type= "Text/javascript" src= "Logger.js" >
<script type= "Text/javascript" >
function Traperror (msg, URI, LN) {
Wrapping an unknown error into an object var error = new error (msg); error.location = URI + ', line: ' + ln;
Add custom attribute Logger.log (error); Warnuser (); return true;
Avoid yellow triangle symbol}window.onerror = traperror;
function foo () {try {riskyoperation ();
} catch (Err) {
Add custom Attribute err.location = Location.href + ', function:foo () ';
Logger.log (err); Warnuser ();
}}function Warnuser () {alert ("An error has occurred while processing this page.") + "Our engineers have been alerted!"); /error Handling Location.href = '/path/to/error/page.html ';

Now that we know how to integrate logs and HTML pages, the rest is how to receive and resolve messages that the client delivers to the server. I used an acceptable CGI script to do this, and in this script I used xml::simple (one of my favorite modules) to parse the submitted data and write the results directly to the error log of the HTTPD (HTTP service program) using Cgi::carp. This way your system administrator will not have to monitor another log. The script also contains some good examples of how to write the response code for 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 is postif ($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";
# when the ' is ' POST and the content type is neither
# URI encoded nor multipart form, the entire post
# is stuffed into one param: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 '});
# This'll change the name of the Carper 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 response code indicates that the operation is a
# success, 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 is not supported ',
-type => ' Text/xml ');
Croak "Unsupported method: $method";}

That's all the code. Now, the next time some problematic JavaScript code slips into the system, you can imagine that your log monitor starts flashing red lights, and your client developer gets a call in the middle of the 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: 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.