Handling Status Codes with an HTTP Object


HTTP status codes have a dual purpose: They are not only useful in the back end for development purposes, but they are also very useful on the front end for providing users with the status of their interactions.

As we briefly covered in Chapter 2, "The Request", the request status of the Ajax object is equivalent to the HTTP status of the file that is being requested. HTTP status codes represent the response from the server based on the status of the file that is being requested. The codes are broken up into five categories, which cover all the possible responses that a server could return to an HTTP request. The HTTP status code categories are listed next; the xx after each number represents other digits which exist in each category and are used to specify a type of error.

  • Informational: 1xx

  • Successful: 2xx

  • Redirection: 3xx

  • Client Error: 4xx

  • Server Error: 5xx

In order to handle these status codes and provide meaningful user feedback, we will create an HTTP object. The object that we will be creating will take the request status from the Ajax object, which will be a number from 1 to 4. It will then return the status code that corresponds with that number value as a string that will contain an explanation of what occurred on the server side. Providing this level of detail is essential when creating web applications because a user should always understand what is happening and what, if anything, went wrong. The HTTP object is fairly simple, but it is quite large because of the level of detail it covers. The following is a condensed version of the object and the methods it contains:

HTTP = {}; HTTP.status = function(_status){} HTTP.getInformationalStatus = function(_status){} HTTP.getSuccessfulStatus = function(_status){} HTTP.getRedirectionStatus = function(_status){} HTTP.getClientErrorStatus = function(_status){} HTTP.getServerErrorStatus = function(_status){}


The HTTP object has been separated into different methods for each response category. To make this object more usable, there is a status method that is used as the access point to the object. All status calls are filtered through this method to the corresponding category to which they belong. Each method takes the status that is passed as a parameter and returns a string response that we, as the developers, choose to respond with. As you will see, the current object has default responses, which represent the literal status code titles, but these can and should ultimately be changed to responses that are more informative and user friendly. Let's take a look at the status method in Listing 9.10 to get an idea of how this method handles delegating the status number value to the corresponding method category.

Listing 9.10. Delegating HTTP Status Codes to the Correct Methods (HTTP.js)

HTTP.status = function(_status) {      var s = _status.toString().split("");      switch(s[0])      {          case "1":              return this.getInformationalStatus(_status);              break;          case "2":              return this.getSuccessfulStatus(_status);              break;          case "3":              return this.getRedirectionStatus(_status);              break;          case "4":              return this.getClientErrorStatus(_status);              break;          case "5":              return this.getServerErrorStatus(_status);              break;          default:              return "An unexpected error has occurred.";      } }

The status code categories are split into different numbers. When the status method receives the _status parameter, it takes the first number from the parameter and locates the corresponding method based on its category number. For example, if the object received a 404 status code value, it would use the first number in the code, which would be the number 4, to locate the appropriate method category and delegate it to that method. In order to use the first number in the status code, we need to convert the number to a string and split it into an array of strings. After we have created the array, we can target its first item, which is the item in the 0 position, and perform a switch on it to match it with the corresponding method category.

HTTP Status Code Categories

The five method categories that the HTTP object consists of correspond to the HTTP status code definition categories. Each of the methods in the object takes a _status parameter, which is used to return the corresponding message. This section will cover the status codes that are handled by each method, but will not go into detail about each status code definition. As a useful reference, I have also added the URL in each method to the status code definition categories, which are defined in detail on the W3C website. The first method that we will focus on, which can be viewed in Listing 9.11, corresponds to the Informational category.

Listing 9.11. Handling Informational Status Codes (HTTP.js)

HTTP.getInformationalStatus = function(_status) {      // Informational 1xx      // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1      switch(_status)      {          case 100:              return "Continue";              break;          case 101:              return "Switching Protocols";              break;          default:              return "An unexpected error has occurred.";      } }

The getInformationalStatus method handles all the informational status codes for the HTTP object. The informational status code category consists of two status codes:

  • Continue: 100

  • Switching Protocols: 101

The second method, named getSuccessfulStatus (see Listing 9.12), handles all the successful HTTP status codes.

Listing 9.12. Handling Successful Status Codes (HTTP.js)

HTTP.getSuccessfulStatus = function(_status) {      // Successful 2xx      // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2      switch(_status)      {          case 200:              return "OK";              break;          case 201:              return "Created";              break;          case 202:              return "Accepted";              break;          case 203:              return "Non-Authoritative Information";              break;          case 204:              return "No Content";              break;          case 205:              return "Reset Content";              break;          case 206:              return "Partial Content";              break;          default:              return "An unexpected error has occurred.";      } }

The successful status code category consists of six status codes:

  • OK: 200

  • Created: 201

  • Accepted: 202

  • Non-Authoritative Information: 203

  • No Content: 204

  • Reset Content: 205

  • Partial Content: 206

The third status code method category is the getredirectionStatus (see Listing 9.13) method.

Listing 9.13. Handling Redirection Status Codes (HTTP.js)

HTTP.getRedirectionStatus = function(_status) {      // Redirection 3xx      // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3      switch(_status)      {           case 300:              return "Multiple Choices";              break;          case 301:              return "Moved Permanently";              break;          case 302:              return "Found";              break;          case 303:              return "See Other";              break;          case 304:              return "Not Modified";              break;          case 305:              return "Use Proxy";              break;          case 307:              return "Temporary Redirect";              break;          default:              return "An unexpected error has occurred.";      } }

The getredirectionStatus method handles all the redirection status codes for the HTTP object. The redirection status code category consists of seven status codes:

  • Multiple Choices: 300

  • Moved Permanently: 301

  • Found: 302

  • See Other: 303

  • Not Modified: 304

  • Use Proxy: 305

  • Temporary Redirect: 307

The fourth method for handling status codes is the getClientErrorStatus (see Listing 9.14) method.

Listing 9.14. Handling Client Error Status Codes (HTTP.js)

HTTP.getClientErrorStatus = function(_status) {      // Client Error 4xx      // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4      switch(_status)      {          case 400:              return "Bad Request";              break;          case 401:              return "Unauthorized";              break;          case 402:              return "Payment Required";              break;          case 403:              return "Forbidden";              break;          case 404:              return "File not found.";              break;          case 405:              return "Method Not Allowed";              break;          case 406:              return "Not Acceptable";              break;          case 407:              return "Proxy Authentication Required";              break;          case 408:              return "Request Timeout";              break;          case 409:              return "Conflict";              break;          case 410:              return "Gone";              break;          case 411:              return "Length Required";              break;          case 412:              return "Precondition Failed";              break;          case 413:              return "Request Entity Too Large";              break;          case 414:              return "Request-URI Too Long";              break;          case 415:              return "Unsupported Media Type";              break;          case 416:              return "Requested Range Not Satisfiable";              break;          case 417:              return "Expectation Failed";              break;          default:              return "An unexpected error has occurred.";      } }

The getClientErrorStatus method handles all the client error status codes for the HTTP object. This status category is intended to present statuses based on an error that occurs from an interaction that a client makes. The client error status code category is the largest of the five categories, consisting of seventeen status codes:

  • Bad Request: 400

  • Unauthorized: 401

  • Payment Required: 402

  • Forbidden: 403

  • File not found: 404

  • Method Not Allowed: 405

  • Not Acceptable: 406

  • Proxy Authentication Required: 407

  • Request Timeout: 408

  • Conflict: 409

  • Gone: 410

  • Length Required: 411

  • Precondition Failed: 412

  • Request Entity Too Large: 413

  • Request-URI Too Long: 414

  • Unsupported Media Type: 415

  • Requested Range Not Satisfiable: 416

  • Expectation Failed: 417

The fifth and final status code category method is named getServerStatus (see Listing 9.15), which consists of all the server error status codes that could be returned from an HTTP request. The difference between the client and the server status code categories is instead of responding with errors based on client interactions, the server status codes are relative to the server and its inability to perform a request.

Listing 9.15. Handling Redirection Status Codes (HTTP.js)

HTTP.getServerErrorStatus = function(_status) {      // Server Error 5xx      // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5      switch(_status)      {          case 500:              return "Internal Server Error";              break;          case 501:              return "Not Implemented";              break;          case 502:              return "Bad Gateway";              break;          case 503:              return "Service Unavailable";              break;          case 504:              return "Gateway Timeout";              break;          case 505:              return "HTTP Version Not Supported";              break;          default:              return "An unexpected error has occurred.";      } }

The server error status code category consists of five status codes:

  • Internal Server Error: 500

  • Not Implemented: 501

  • Bad Gateway: 502

  • Service Unavailable: 503

  • Gateway Timeout: 504

  • HTTP Version Not Supported: 505

As you can see, the HTTP object is fairly simple, yet it is fairly large as well due to the fact that it handles every single status code that an HTTP request could possibly return. This object will save a lot of coding time; all that you must do for your applications is provide a custom message or even an action based on the code.

Using the HTTP Object

Adding the HTTP object to the Ajax engine is extremely simple after the JavaScript file has been imported into the current document. We will need to call only a single method, which will provide the status feedback as a string. Listing 9.16 shows how to return the status to the Ajax requestor.

Listing 9.16. Returning the HTTP Status As a String (Ajax.js)

Ajax.checkReadyState = function(_id) {    switch(this.request.readyState)    {        case 1:            document.getElementById(_id).innerHTML = 'Loading ...';            break;        case 2:            document.getElementById(_id).innerHTML = 'Loading ...';            break;        case 3:            document.getElementById(_id).innerHTML = 'Loading ...';            break;        case 4:            AjaxUpdater.isUpdating = false;            document.getElementById(_id).innerHTML = '';            return HTTP.status(this.request.status);        default:            document.getElementById(_id).innerHTML = "An unexpected error has occurred.";    } }

Now that we have the HTTP object created, we can begin to return meaningful status codes to requesting objects as feedback to the user or we can use these status codes to provide the user with other options. For instance, let's say that we have an application that is attached to a shopping cart and we receive a 402: Payment Required response from the server. We could either redirect the user to a payment page or dynamically write a payment form to the page through DHTML. Another possibility could be a 401: Unauthorized response, which we could handle by redirecting the user to a login page or, again, we could use DHTML to present a form to the user for login/registration without refreshing the page. When the user logs in or registers, we could send the request through Ajax. After we receive a successful response, we could present the user with the original data she was requesting.

There is a huge difference between providing the user with feedback versus providing her with options. When we provide a user with feedback, she does not have any options and is usually left wondering what to do next. If we provide the user with options, we make the process much more intuitive and allow the user to progress on her own without worrying about reading cryptic messages from the server side. In fact, those cryptic messages also take time for developers to write. Rather, developers could be planning their next response to provide the user with a new option. HTTP status codes are just one of the features that make Ajax so powerful, yet they are very seldom a topic of conversation. If you think of the example situations in this context, you can accomplish some fairly complex user interaction scenarios that will dynamically occur based on your users' interactions after your project has been completed. It will become a living application that reacts based on the current users' status and interactions.



Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net