Errors and Ajax

Source: Internet
Author: User
Tags object contains error handling header implement net unsupported window
Ajax| Error

Even if you haven't heard it yet, Ajax has become the hottest word in the Web technology world. 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 in particular, as well as support for XML DOM, although as always: Microsoft (Microsoft) A slightly different implementation is used and there are 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 Sword
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 {
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 {
clean-up work
}
}
Window.onerror = HandleError; A safety net that catches errors
function handleerror (message, URI, line) {
Prompts the user that the page may not respond correctly
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 construction 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 an XML document
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;
}

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.

Journaling Methods for logger classes
function log (err) {
Sniffing environment
if (window. XMLHttpRequest) This.req = new XMLHttpRequest ();
else if (window. ActiveXObject) This.req =
New ActiveXObject ("Microsoft.XMLHTTP");
else return; return without work
Method of determination and URI
This.req.open ("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 ');
function to call when the request is complete
This.req.onreadystatechange = errorlogged;
This.req.send (This.errortoxml (err));
If the request cannot be completed in 10 seconds,
Transaction processing Required
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
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.

Try as you may, but if you have a connection error, give it up.
function Abortlog () {
Logger.req.abort ();
Alert ("Attempt to log the error timed out.");
}

Called when the request state has changed
function errorlogged () {
if (logger.req.readyState!= 4) return;
Window.cleartimeout (logger.timeout);
Request complete
if (Logger.req.status >= 400)
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:

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.

<script type= "Text/javascript" src= "Logger.js" ></script>
<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; Adding custom properties
Logger.log (Error);
Warnuser ();
return true; Avoid yellow triangle symbols
}
Window.onerror = Traperror;

function foo () {
try {
Riskyoperation ();
} catch (Err) {
Adding custom properties
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 ';
}
</script>

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 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";
}
# 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 developers get 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: 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.