Error handling mechanism of Ajax

Source: Internet
Author: User
Tags define object error handling header html page include unsupported window
Ajax| Error | Error handling

The core of the AJAX framework component is the XMLHttpRequest JavaScript object, which allows the client developer to send and receive XML documents over HTTP without disrupting user action and without exploiting hidden pages. Now, some people may feel fear because it suddenly allows client developers who are likely to use validated forms and animated images too much to pass XML documents and process HTTP header information, but without risk there is no gain. We don't have to be afraid, I'll demonstrate how to use XMLHttpRequest to add some previously impossible, unworkable features that also reduce errors and improve 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, Opera), although in general, Microsoft has a slight increase in its implementation and requires some special processing. Even though more of our friends have directly implemented XMLHttpRequest, IE asks you to instantiate a activexobject with the same attributes. An overview and a list of all the features can be found on the Apple developer relationship 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. (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 {




There are many potential users of this powerful feature, and the search for what it might do is just beginning. But before you try to build XML functionality on the Web, I suggest you set up a "safety net" to keep your ambitions (ideas) from being hit.

JavaScript Error Handling Basics

JavaScript has been there for a long time, and its earlier versions are primitive, lacking features, just implemented. The latest browsers not only support the Try/catch/finally keyword in C + + and Java, but also implement the OnError event, which can capture any errors that occur at run time. The use of it is very straightforward:

function riskybusiness () {

try {

RiskyOperation1 ();

RiskyOperation2 ();

catch (e) {

E is an error-type object with at least two properties: name and message

finally {

Purge messages



Window.onerror = HandleError; Catch all the wrong safety nets

function handleerror (message, URI, line) {

Prompts the user that this page may not respond correctly

return true; Stop the default message


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 () {




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 ' +

' ' + + ' \ 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 ("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:

function Traperror (msg, URI, LN) {

Wrapping our unknown error in an object

var error = new error (MSG);

Error.location = URI + ', line: ' + ln; Adding custom properties

Logger.log (Error);

Warnuser ();

return true; Stop Yellow triangle


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!");

Location.href = '/path/to/error/page.html ';


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,

#那么整个post会被填充到一个参数中: 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.

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.