Tuesday, March 29, 2005

Make your Apache HTTP errors more Ajax-friendly

Applications that use remote scripting or Ajax-style communications can have problems when things go wrong at the server end. How does one detect a 404 or 500 error inside your hidden IFRAME, and how can an application be designed to handle such an error?

A client-side developer would probably suggest walking the DOM tree out to the IFRAME document and looking for the status text. But why not make it easier by having the server hand back HTTP errors to your application as JavaScript? This can be done with relative ease with Apache (I'm sure other servers can be configured similarly) with three basic steps:

  1. Create a custom error page
  2. Include JavaScript in the error page that interacts with the application (via the containing frame or IFRAME)
  3. Use Apache's ErrorDocument directive to tell the server to deliver the custom error page when an error occurs

Below is a sample error page written in PHP. Apache provides the basic variables needed to determine the status; here, we just pluck them from PHP's global variables and plug them into a JavaScript block. Once loaded, the JavaScript looks for an onServerError handler in the parent window (assuming the page request is made from a frame or IFRAME) and invokes it with the HTTP status information.

<?
  /* error.php */
  /* this line ensures the client gets the HTTP status */
  header("Status:" . $REDIRECT_STATUS);
?>
<!-- include DOCTYPE of choice here -->
<html>
<head>
  <title>Error <? print $REDIRECT_STATUS; ?></title>
  <script>
    var win = (window.parent) ? window.parent : window;
    if (win.onServerError) {
      win.onServerError(
        {
          status:'<? print $REDIRECT_STATUS; ?>',
          url:   '<? print $REDIRECT_URL; ?>',
        }
      );
    }
  </script>
</head>
<body>
  <h1>Error <? print $REDIRECT_STATUS; ?></h1>
  <p>
     This page should have invoked a 
     JavaScript onServerError handler 
     if one was provided.
  </p>
</body>
</html>

We'll save this file as error.php and place it in a directory named /rs-errors/. Next, we have to tell Apache to use our error page for selected HTTP error statuses. We can do this by adding ErrorDocument directives to an .htaccess file placed inside the directory at which our remote scripting requests are targeted. For example, if you're sending requests to http://appserver.example.com/api you'll want to put these in the .htaccess file for that directory:

ErrorDocument 404 /rs-errors/error.php
ErrorDocument 500 /rs-errors/error.php

Now, if a 404 or 500 error occurs inside of /api Apache will use our error.php as the error document served to the browser.

It should be relatively simple to implement this in a JavaScript application now:

<script>
  function onServerError(e) {
    switch (e.status) {
      case '500':
        // handle a 500 error here
        break;
      case '404':
        // handle a 404 error here
        break;
    }
  }
</script>

...

<iframe src="http://appserver.example.com/api/some-bogus-request-here">
</iframe>

When the IFRAME attempts to load the bogus URI, Apache will throw a 404 error and invoke error.php. The JavaScript in the head of our error page will attempt the onServerError handler defined in the application. The application can now decide how to best communicate the error state to the user without appearing broken.

Caveat: don't forget that IE will attempt to serve up its own custom 500 page from the local machine, so it might be a good idea to pad your error page with 512K 512 bytes (or more) of whitespace or commented text to convince IE that your error is the one to show.

If you prefer an "Ajax (The X Is For 'XML' Dammit!)" approach, you can easily write your custom error page to deliver HTTP statuses as an XML payload instead of JavaScript. I prefer JavaScript myself since I don't have to parse it, but XML might be preferred if you're sharing data across different apps on different platforms.

Reference:

51 Comments:

At 3:12 AM, Anonymous Canis said...

According to the Microsoft article you linked to, you need 512 _bytes_ of padding, not 512K of padding as stated in your post.
(Which is fortunate, really.)

 
At 5:45 AM, Anonymous Anonymous said...

Surely the client JavaScript code should already be handling the XMLHttpRequest status codes (using the status property) when the request is received? The mechanism you propose sounds a bit cumbersome to me.

 
At 8:14 AM, Blogger scottandrew said...

canis: oops, fixed, thanks :)

anon: the Ajax appreach doesn't necessarily mean the client app is using XMLHttpRequest. The sample code above assumes you're using a frame or an IFRAME for client-server transport, without XMLHttpRequest.

 
At 6:46 AM, Blogger WorldTrader said...

I found a new article digital site submit. Post your Articles, Get Free Content. article digital site submit

 
At 1:50 AM, Blogger harvir said...

Veryyyyyyyyy nice blog i kinda like it coz it got alot of information that can be useful for me very informative you go guys and one thing more i got a site that i prefer to everybody maybe you will like it to go have a look in your free timeBest rated home based business

 
At 2:43 AM, Blogger harvir said...

Veryyyyyyyyy nice blog i kinda like it coz it got alot of information that can be useful for me very informative you go guys and one thing more i got a site that i prefer to everybody maybe you will like it to go have a look in your free timeHome based small business

 
At 8:04 PM, Blogger Jack Naka said...

Just thought i would say hi from Japan. Doing some blog surfing and found your site. Im looking for some cool styles of fashion week for my own blog. Theres some really amazing blogs about. if you have time check out my site you will find information on fashion week. Well when i get my blog running hope you come and check it out.

 
At 10:51 PM, Blogger Answering Service said...

Hey, nice blog and great info!
Did some digging. Here's another spanish article
spanish article
site that people interested in spanish article
will be happy to find.
Come and check it out if you get time I would really appreciate it :-)

 
At 7:51 PM, Blogger Kim said...

Hey, I really like the quality of your blog. Very interesting indeed!

I own a article submission directory related site. It is mostly about article submission directory information.

Come to see us when you get time.

 
At 9:03 PM, Blogger Infactahost.com said...

Hey, you have a great blog here! I'm definitely going to bookmark you!

I have a web hosting review site/blog. It pretty much covers web hosting review related stuff.

Come and check it out if you get time :-)

 
At 9:04 PM, Blogger Infactahost.com said...

Hey, you have a great blog here! I'm definitely going to bookmark you!

I have a internet service provider hosting site/blog. It pretty much covers internet service provider hosting related stuff.

Come and check it out if you get time :-)

 
At 12:29 PM, Blogger tittadigirolamo said...

Free wordpress blog at theblog.cc Free Blog.

 
At 4:00 PM, Blogger thebigsearch said...

With our Blog Hosting Script you can now create and mantain your free blog community.

 
At 9:04 PM, Blogger Swingin80 said...

Cool blog you have. I have a work at home typist related site. Check it out if you get a chance. The URL is work at home typist

 
At 7:50 PM, Blogger Doniette said...

How would you like to know about a Walking Stick resource, that displays all the Walking Stick information on one website? Check out
Walking Stick today. Not only do they have a good fitness book section, but they also have great articles on fitness. I was really impressed with the resources their webmster put together.

 
At 8:04 AM, Blogger clicking4man said...

I enjoyed reading your blog. There is a lot of useful information about website indexed in it. We offer Turnkey Websites and Reliable Hosting. We also provide a blogging service that will help your site get indexed fast and keep the search engines visiting your site. Click here for more information about website indexed.
Thank you
TWP Admin

 
At 1:57 PM, Blogger Global Names said...

Hey, you have a great blog here! I'm definitely going to bookmark you!
I have a domain name registration and hosting site. You better check it out some time.

 
At 11:00 PM, Blogger TheDevilIsInTheDetails said...

domain name servicesGreetings! I have to say that I'm quite impressed that your blog ranks so highly for domain name services . Because it does (And I'm wacky like that) I thought it might be beneficial to point out this resource for domain name services

 
At 2:48 AM, Blogger GooglePlexMan said...

Hey, I saw your blog and thought it was great. I thought you might want to look at some great Home Business Connection
. There's a lot of buzz about the new Home Business Connection
and maybe some of your readers will want to know. Best wishes to you.

 
At 1:38 PM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 2:58 PM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 4:41 PM, Blogger Interad said...

Great blog!, Good to see you.
I am sure that your blog page looks great to me which mean looking crowded so,
My site - Global Domain Name Registrations - open event during one month domain registrar. You better check it out some time.

 
At 5:29 PM, Blogger Freddies Blog said...

Last month I made $12,124 with Google Adsense...Click
here for free on how you can do the same!

 
At 7:16 PM, Blogger betterlovemaking said...

I enjoyed reading your blog. There is a lot of useful information about seo in it. We offer Turnkey Websites and Reliable Hosting. We also provide a blogging service that will help your site get indexed fast and keep the search engines visiting your site. Click here for more information about seo.
Thank you
TWP Admin

 
At 5:58 PM, Blogger TWPAdmin said...

I enjoyed reading your blog. There is a lot of useful information about blogging service in it. We offer Turnkey Websites and Reliable Hosting. We also provide a blogging service that will help your site get indexed fast and keep the search engines visiting your site. Click here for more information about blogging service.
Thank you
TWP Admin

 
At 11:38 PM, Blogger rokkgod said...

I love this blog you got here. I run a movie review website and need people to do movie reviews.Movie Reviews. Thanks...sorry to be self promoting..at least you get some fresh text content.

 
At 6:48 AM, Blogger Mizambar 6294 said...

Last month, I earned $12,124 from Google Adsense, click here for free information to find out how you can do the same

 
At 2:29 PM, Blogger Freddies Blog said...

Last month, I earned $12,124 from Google Adsense, click here for free information to find out how you can do the same

 
At 7:01 PM, Blogger TheDevilIsInTheDetails said...

Not much to say besides the fact that coming to Register Better would be a good decision in regards to domain controller !

 
At 7:36 PM, Blogger tipsonrelationships said...

I enjoyed reading your blog. There is a lot of useful information about home based business in it. We offer Turnkey Websites and Reliable Hosting. We also provide a blogging service that will help your site get indexed fast and keep the search engines visiting your site. Click here for more information about home based business.
Thank you
TWP Admin

 
At 2:03 PM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 8:44 AM, Blogger Juno-Regina said...

This comment has been removed by a blog administrator.

 
At 8:45 AM, Blogger Juno-Regina said...

This comment has been removed by a blog administrator.

 
At 7:57 PM, Blogger Tony said...

Nice Apache info. I myself have worked with apache enough to know any tip I can get it well worth it.

Come visit my article submission directory sometime, great info there, and I always love people submitting more.

 
At 5:40 AM, Blogger HiiFii Webservices said...

I liked you Blog so much,so i also wanted to show you some good resourses on the net.
Learn to earn 90000$/Month
For which you may also see my Personal Website
Here.
and for a Personal Education Career Tools
free Study Database.
This site is for seeing the
Hifi Electronics.
And this is for
World Class Gadgets

 
At 4:35 PM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 4:37 PM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 12:17 AM, Blogger HiiFii Webservices said...

Please See these new Sites purchased by me.
Sluze
Adsense Talk
DomainBar
HostBoard
Review my Site

Please Check out my new Free Softwares WebsiteAll Free Softwares

please check my latest Blog on Increasing memory Memory Gain

 
At 8:17 AM, Blogger Roberto Iza Valdes said...

This comment has been removed by a blog administrator.

 
At 2:43 AM, Blogger http://www.debt-consolidation.com said...

Student Consolidation
Debt Consolidation Loan can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period

 
At 12:38 PM, Blogger Bayarealawyers said...

Debt Settlement
Debt Relief can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period
http://www.debt-consolidation.com
Debt Settlement
Debt Relief can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period
http://www.debt-consolidation.com

 
At 12:39 PM, Blogger Bayarealawyers said...

Debt Settlement
Debt Relief can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period
http://www.debt-consolidation.com

 
At 7:18 PM, Blogger http://www.debt-consolidation.com said...

Debt Help
Debt Consolidation can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans.
http://www.debt1consolidation.com

 
At 5:25 AM, Blogger telaat said...

Some popular casino games online you can find at web casino but the most gambling
casino games is fun to play, the news promoting how to play poker and another online casino games
so the world's population choosing play casino fun online games!!

 
At 3:49 AM, Blogger http://www.debt-consolidation.com said...

Debt Consolidation
Debt Help can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period
http://www.debt1consolidation.com
Debt Consolidation
Debt Help can help you reduce your interest burden by charging an interest rate lower than the rate on your existing loans. Debt consolidation loan can also allow you to make small monthly payments by extending the loan period
http://www.debt1consolidation.com

 
At 2:14 AM, Blogger Alex said...

how determine $REDIRECT_STATUS ?
in
header("Status:" . $REDIRECT_STATUS);

 
At 4:14 PM, Blogger http://www.debt-consolidation.com said...

FREE QUOTE DEBT HELP APPLY NOW
Credit Card Debt Consolidation
Credit Card Debt Help can help you reduce your interest burden by charging an interest rate lower than the rate on your existing debt. Debt consolidation can also allow you to make small monthly payments by extending the debt period...
http://www.debt-consolidation.com



FREE QUOTE DEBT HELP APPLY NOW

 
At 9:12 AM, Blogger iza roberto iza said...

This comment has been removed by the author.

 
At 11:15 PM, Blogger Iza Firewall said...

This comment has been removed by the author.

 
At 6:17 PM, Blogger satxxkenn said...

Cool blog - Check out my site if you need help finding a good low interest credit card. Credit Cards

 
At 2:15 PM, Blogger milf said...

black mold exposureblack mold symptoms of exposurewrought iron garden gatesiron garden gates find them herefine thin hair hairstylessearch hair styles for fine thin hairnight vision binocularsbuy night vision binocularslipitor reactionslipitor allergic reactionsluxury beach resort in the philippines

afordable beach resorts in the philippineshomeopathy for eczema.baby eczema.save big with great mineral makeup bargainsmineral makeup wholesalersprodam iphone Apple prodam iphone prahacect iphone manualmanual for P 168 iphonefero 52 binocularsnight vision Fero 52 binocularsThe best night vision binoculars here

night vision binoculars bargainsfree photo albums computer programsfree software to make photo albumsfree tax formsprintable tax forms for free craftmatic air bedcraftmatic air bed adjustable info hereboyd air bedboyd night air bed lowest pricefind air beds in wisconsinbest air beds in wisconsincloud air beds

best cloud inflatable air bedssealy air beds portableportables air bedsrv luggage racksaluminum made rv luggage racksair bed raisedbest form raised air bedsaircraft support equipmentsbest support equipments for aircraftsbed air informercialsbest informercials bed airmattress sized air beds

bestair bed mattress antique doorknobsantique doorknob identification tipsdvd player troubleshootingtroubleshooting with the dvd playerflat panel television lcd vs plasmaflat panel lcd television versus plasma pic the bestThe causes of economic recessionwhat are the causes of economic recessionadjustable bed air foam The best bed air foam

hoof prints antique equestrian printsantique hoof prints equestrian printsBuy air bedadjustablebuy the best adjustable air bedsair beds canadian storesCanadian stores for air beds

migraine causemigraine treatments floridaflorida headache clinicdrying dessicantair drying dessicantdessicant air dryerpediatric asthmaasthma specialistasthma children specialistcarpet cleaning dallas txcarpet cleaners dallascarpet cleaning dallas

 

Post a Comment

<< Home