Handling Errors

 

The WebRequest and WebResponse classes throw both system exceptions (such as ArgumentException) and Web-specific exceptions (which are WebExceptions thrown by the GetResponse method).

Each WebException includes a Status property that contains a value from the WebExceptionStatus enumeration. You can examine the Status property to determine the error that occurred and take the proper steps to resolve the error.

The following table describes the possible values for the Status property.

StatusDescription
ConnectFailureThe remote service could not be contacted at the transport level.
ConnectionClosedThe connection was closed prematurely.
KeepAliveFailureThe server closed a connection made with the Keep-alive header set.
NameResolutionFailureThe name service could not resolve the host name.
ProtocolErrorThe response received from the server was complete but indicated an error at the protocol level.
ReceiveFailureA complete response was not received from the remote server.
RequestCanceledThe request was canceled.
SecureChannelFailureAn error occurred in a secure channel link.
SendFailureA complete request could not be sent to the remote server.
ServerProtocolViolationThe server response was not a valid HTTP response.
SuccessNo error was encountered.
TimeoutNo response was received within the time-out set for the request.
TrustFailureA server certificate could not be validated.
MessageLengthLimitExceededA message was received that exceeded the specified limit when sending a request or receiving a response from the server.
PendingAn internal asynchronous request is pending.
PipelineFailureThis value supports the .NET Framework infrastructure and is not intended to be used directly in your code.
ProxyNameResolutionFailureThe name resolver service could not resolve the proxy host name.
UnknownErrorAn exception of unknown type has occurred.

When the Status property is WebExceptionStatus.ProtocolError, a WebResponse that contains the response from the server is available. You can examine this response to determine the actual source of the protocol error.

The following example shows how to catch a WebException.

try   
{  
    // Create a request instance.  
    WebRequest myRequest =   
    WebRequest.Create("http://www.contoso.com");  
    // Get the response.  
    WebResponse myResponse = myRequest.GetResponse();  
    //Get a readable stream from the server.   
    Stream sr = myResponse.GetResponseStream();  
  
    //Read from the stream and write any data to the console.  
    bytesread = sr.Read( myBuffer, 0, length);  
    while( bytesread > 0 )   
    {  
        for (int i=0; i<bytesread; i++) {  
            Console.Write( "{0}", myBuffer[i]);  
        }  
        Console.WriteLine();  
        bytesread = sr.Read( myBuffer, 0, length);  
    }  
    sr.Close();  
    myResponse.Close();  
}  
catch (WebException webExcp)   
{  
    // If you reach this point, an exception has been caught.  
    Console.WriteLine("A WebException has been caught.");  
    // Write out the WebException message.  
    Console.WriteLine(webExcp.ToString());  
    // Get the WebException status code.  
    WebExceptionStatus status =  webExcp.Status;  
    // If status is WebExceptionStatus.ProtocolError,   
    //   there has been a protocol error and a WebResponse   
    //   should exist. Display the protocol error.  
    if (status == WebExceptionStatus.ProtocolError) {  
        Console.Write("The server returned protocol error ");  
        // Get HttpWebResponse so that you can check the HTTP status code.  
        HttpWebResponse httpResponse = (HttpWebResponse)webExcp.Response;  
        Console.WriteLine((int)httpResponse.StatusCode + " - "  
           + httpResponse.StatusCode);  
    }  
}  
catch (Exception e)   
{  
    // Code to catch other exceptions goes here.  
}  

Applications that use the Socket class throw SocketExceptions when errors occur on the Windows socket. The TCPClient, TCPListener, and UDPClient classes are built on top of the Socket class and throw SocketExceptions as well.

When a SocketException is thrown, the SocketException class sets the ErrorCode property to the last operating system socket error that occurred. For more information about socket error codes, see the Winsock 2.0 API error code documentation in MSDN.

Exception Handling Fundamentals
Requesting Data

Show: