Handling Network Errors


Although the program in the preceding section is correct, it is not resilient. Even the simplest network error will cause it to end abruptly. Although this isn’t a problem for the example programs shown in this chapter, it is something that must be avoided in real-world applications. To fully handle all network exceptions that the program might generate, you must monitor calls to Create( ), GetResponse( ), and GetResponseStream( ). It is important to understand that the exceptions that can be generated depend upon the protocol being used. The following discussion describes the errors possible when using HTTP.

Exceptions Generated by Create( )

The Create( ) method defined by WebRequest can generate four exceptions. If the protocol specified by the URI prefix is not supported, then NotSupportedException is thrown. If the URI format is invalid, UriFormatException is thrown. If the user does not have the proper authorization, a System.Security.SecurityException will be thrown. Create( ) can also throw an ArgumentNullException if it is called with a null reference, but this is not an error generated by networking.

Exceptions Generated by GetReponse( )

A number of errors can occur when obtaining an HTTP response by calling GetResponse( ). These are represented by the following exceptions: InvalidOperationException, ProtocolViolationException, NotSupportedException, and WebException. Of these, the one of most interest is WebException.

WebException has two properties that relate to network errors: Response and Status. You can obtain a reference to the WebResponse object inside an exception handler through the Response property. For the HTTP protocol, this object describes the error. It is defined like this:

 public WebResponse Response { get; }

When an error occurs, you can use the Status property of WebException to find out what went wrong. It is defined like this:

 public WebExceptionStatus Status {get; }

WebExceptionStatus is an enumeration that contains the following values:

CacheEntryNotFound

ConnectFailure

ConnectionClosed

KeepAliveFailure

MessageLengthLimitExceeded

NameResolutionFailure

Pending

PipelineFailure

ProtocolError

ProxyNameResolutionFailure

ReceiveFailure

RequestCanceled

RequestProhibitedByCachePolicy

RequestProhibitedByProxy

SecureChannelFailure

SendFailure

ServerProtocolViolation

Success

Timeout

TrustFailure

UnknownError

Once the cause of the error has been determined, your program can take appropriate action.

Exceptions Generated by GetResponseStream( )

For the HTTP protocol, the GetResponseStream( ) method of WebResponse can throw a ProtocolViolationException, which in general means that some error occurred relative to the specified protocol. As it relates to GetResponseStream( ), it means that no valid response stream is available. An ObjectDisposedException will be thrown if the response has already been disposed. Of course, an IOException could occur while reading the stream.

Using Exception Handling

The following program adds handlers for the network exceptions just described to the example shown earlier:

 // Handle network exceptions. using System; using System.Net; using System.IO; class NetExcDemo {   public static void Main() {     int ch;     try {       // First, create a WebRequest to a URI.       HttpWebRequest req = (HttpWebRequest)              WebRequest.Create("http://www.McGraw-Hill.com");       // Next, send that request and return the response.       HttpWebResponse resp = (HttpWebResponse)              req.GetResponse();       // From the response, obtain an input stream.       Stream istrm = resp.GetResponseStream();       /* Now, read and display the html present at          the specified URI.  So you can see what is          being displayed, the data is shown          400 characters at a time.  After each 400          characters are displayed, you must press          ENTER to get the next 400. */       for(int i=1; ; i++) {         ch =  istrm.ReadByte();         if(ch == -1) break;         Console.Write((char) ch);         if((i%400)==0) {           Console.Write("\nPress Enter.");           Console.ReadLine();         }       }       // Close the Response. This also closes istrm.       resp.Close();     } catch(WebException exc) {       Console.WriteLine("Network Error: " + exc.Message +                         "\nStatus code: " + exc.Status);     } catch(ProtocolViolationException exc) {       Console.WriteLine("Protocol Error: " + exc.Message);     } catch(UriFormatException exc) {       Console.WriteLine("URI Format Error: " + exc.Message);     } catch(NotSupportedException exc) {       Console.WriteLine("Unknown Protocol: " + exc.Message);     } catch(IOException exc) {       Console.WriteLine("I/O Error: " + exc.Message);     } catch(System.Security.SecurityException exc) {       Console.WriteLine("Security Exception: " + exc.Message);     } catch(InvalidOperationException exc) {       Console.WriteLine("Invalid Operation: " + exc.Message);     }   } }

Now the exceptions that the networking methods might generate have been caught. For example, if you change the call to Create( ) as shown here:

 WebRequest.Create("http://www.McGraw-Hill.com/moonrocket");

and then recompile and run the program, you will see this output:

 Network Error: The remote server returned an error: (404) Not Found. Status code: ProtocolError

Since the McGraw-Hill.com web site does not have a directory called “moonrocket,” this URI is not found, as the output confirms.

To keep the examples short and uncluttered, most of the programs in this chapter will not contain full exception handling. However, your real-world applications should.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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