如何管理客户端和服务器错误?

时间:2016-03-01 20:20:26

标签: c# exception-handling

我有这段代码:

public static string Connect(string Uri)
{
    try
    {
        HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
        connection.Method = "GET";
        string response;

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)    
        using (var responseStream = new StreamReader(response.GetResponseStream()))
        {
            responseText = responseStream.ReadToEnd();
        }

        return response;
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

如果API返回200 http状态,则会正确返回response变量,而如果我遇到客户端错误400500,则代码会出现异常。我希望在try中管理此例外而不是Console.WriteLine,这样做会有变化吗?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,以最大限度地减少重复代码并将异常处理为尽可能接近抛出的位置。

public static string Connect(string Uri)
{
   HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
    connection.Method = "GET";
    string response;

    HttpWebResponse response = null;
    try
    {
        response = request.GetResponse() as HttpWebResponse
    }
    catch (WebException ex)
    {
        response = ex.Response;
    }

    using (response)    
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
        responseText = responseStream.ReadToEnd();
    }

    return response;
}