Tratando errosHandling Errors

As classes WebRequest e WebResponse geram exceções do sistema (como ArgumentException) e exceções específicas à Web (que são WebException geradas pelo método GetResponse).The WebRequest and WebResponse classes throw both system exceptions (such as ArgumentException) and Web-specific exceptions (which are WebException thrown by the GetResponse method).

Cada WebException inclui uma propriedade Status que contém um valor da enumeração WebExceptionStatus.Each WebException includes a Status property that contains a value from the WebExceptionStatus enumeration. Examine a propriedade Status para determinar o erro ocorrido e execute as etapas apropriadas para resolver o erro.You can examine the Status property to determine the error that occurred and take the proper steps to resolve the error.

A tabela a seguir descreve os possíveis valores para a propriedade Status.The following table describes the possible values for the Status property.

StatusStatus DescriçãoDescription
ConnectFailureConnectFailure O serviço remoto não pôde ser contatado no nível do transporte.The remote service could not be contacted at the transport level.
ConnectionClosedConnectionClosed A conexão foi fechada prematuramente.The connection was closed prematurely.
KeepAliveFailureKeepAliveFailure O servidor fechou uma conexão estabelecida com o conjunto de cabeçalhos Keep-alive.The server closed a connection made with the Keep-alive header set.
NameResolutionFailureNameResolutionFailure O serviço de nomes não pôde resolver o nome do host.The name service could not resolve the host name.
ProtocolErrorProtocolError A resposta recebida do servidor estava completa, mas indicava um erro no nível do protocolo.The response received from the server was complete but indicated an error at the protocol level.
ReceiveFailureReceiveFailure Não foi recebida uma resposta completa do servidor remoto.A complete response was not received from the remote server.
RequestCanceledRequestCanceled A solicitação foi cancelada.The request was canceled.
SecureChannelFailureSecureChannelFailure Ocorreu um erro em um link de canal seguro.An error occurred in a secure channel link.
SendFailureSendFailure Não foi possível enviar uma solicitação completa para o servidor remoto.A complete request could not be sent to the remote server.
ServerProtocolViolationServerProtocolViolation A resposta do servidor não era uma resposta HTTP válida.The server response was not a valid HTTP response.
SucessoSuccess Nenhum erro foi encontrado.No error was encountered.
Tempo limiteTimeout Nenhuma resposta foi recebida no tempo limite definido para a solicitação.No response was received within the time-out set for the request.
TrustFailureTrustFailure Não foi possível validar um certificado do servidor.A server certificate could not be validated.
MessageLengthLimitExceededMessageLengthLimitExceeded Foi recebida uma mensagem que ultrapassa o limite especificado ao enviar uma solicitação ou receber uma resposta do servidor.A message was received that exceeded the specified limit when sending a request or receiving a response from the server.
PendentePending Uma solicitação assíncrona interna está pendente.An internal asynchronous request is pending.
PipelineFailurePipelineFailure Esse valor dá suporte à infraestrutura .NET Framework e não se destina a ser usado diretamente no código.This value supports the .NET Framework infrastructure and is not intended to be used directly in your code.
ProxyNameResolutionFailureProxyNameResolutionFailure O serviço de resolvedor de nome não pôde resolver o nome de host do proxy.The name resolver service could not resolve the proxy host name.
UnknownErrorUnknownError Ocorreu uma exceção de tipo desconhecido.An exception of unknown type has occurred.

Quando a propriedade Status é WebExceptionStatus.ProtocolError, uma WebResponse que contém a resposta do servidor está disponível.When the Status property is WebExceptionStatus.ProtocolError, a WebResponse that contains the response from the server is available. Examine essa resposta para determinar a origem real do erro de protocolo.You can examine this response to determine the actual source of the protocol error.

O exemplo a seguir mostra como capturar uma WebException.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.  
}  
Try  
    ' Create a request instance.  
    Dim myRequest As WebRequest = WebRequest.Create("http://www.contoso.com")  
    ' Get the response.  
    Dim myResponse As WebResponse = myRequest.GetResponse()  
    'Get a readable stream from the server.
    Dim sr As Stream = myResponse.GetResponseStream()  
  
    Dim i As Integer
    'Read from the stream and write any data to the console.  
    bytesread = sr.Read(myBuffer, 0, length)  
    While bytesread > 0  
        For i = 0 To bytesread - 1  
            Console.Write("{0}", myBuffer(i))  
        Next i  
        Console.WriteLine()  
        bytesread = sr.Read(myBuffer, 0, length)  
    End While  
    sr.Close()  
    myResponse.Close()  
Catch webExcp As WebException  
    ' 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.  
    Dim status As WebExceptionStatus = 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 Then  
        Console.Write("The server returned protocol error ")  
        ' Get HttpWebResponse so that you can check the HTTP status code.  
        Dim httpResponse As HttpWebResponse = _  
           CType(webExcp.Response, HttpWebResponse)  
        Console.WriteLine(CInt(httpResponse.StatusCode).ToString() & _  
           " - " & httpResponse.StatusCode.ToString())  
    End If  
Catch e As Exception  
    ' Code to catch other exceptions goes here.  
End Try  

Os aplicativos que usam a classe Socket geram SocketException quando ocorrem erros no soquete do Windows.Applications that use the Socket class throw SocketException when errors occur on the Windows socket. As classes TcpClient, TcpListener e UdpClient são criadas com base na classe Socket e geram SocketExceptions também.The TcpClient, TcpListener, and UdpClient classes are built on top of the Socket class and throw SocketExceptions as well.

Quando uma SocketException é gerada, a classe SocketException define a propriedade ErrorCode com o último erro de soquete do sistema operacional ocorrido.When a SocketException is thrown, the SocketException class sets the ErrorCode property to the last operating system socket error that occurred. Para obter mais informações sobre códigos de erro de soquete, consulte a documentação de códigos de erro da API do Winsock 2.0 no MSDN.For more information about socket error codes, see the Winsock 2.0 API error code documentation in MSDN.

Confira tambémSee also