35

C#と.NET 4.5を使用して404エラーが発生した場合に、のメソッドresponseによって返されるものを特定しようとしています。HttpClientGetAsync

現在、404やタイムアウトなどのエラーのステータスではなく、エラーが発生したことしかわかりません。

現在、私のコードは次のようになっています。

    static void Main(string[] args)
    {
        dotest("http://error.123");
        Console.ReadLine();
    }

    static async void dotest(string url)
    {
        HttpClient client = new HttpClient();

        HttpResponseMessage response = new HttpResponseMessage();

        try
        {
            response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode.ToString());
            }
            else
            {
                // problems handling here
                string msg = response.IsSuccessStatusCode.ToString();

                throw new Exception(msg);
            }

        }
        catch (Exception e)
        {
            // .. and understanding the error here
            Console.WriteLine(  e.ToString()  );                
        }
    }

私の問題は、例外を処理できず、そのステータスやその他の問題の詳細を特定できないことです。

例外を適切に処理し、発生したエラーを解釈するにはどうすればよいですか?

4

2 に答える 2

58

StatusCode応答のプロパティを確認するだけです。

static async void dotest(string url)
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode.ToString());
        }
        else
        {
            // problems handling here
            Console.WriteLine(
                "Error occurred, the status code is: {0}", 
                response.StatusCode
            );
        }
    }
}
于 2013-02-01T12:16:34.163 に答える
1

プロパティresponse.StatusCodeHttpStatusCode列挙型です。

これは私が揚げ物の名前を取得するために使用するコードです

if (response != null)
{
    int numericStatusCode = (int)response.StatusCode;

    // like: 503 (ServiceUnavailable)
    string friendlyStatusCode = $"{ numericStatusCode } ({ response.StatusCode })";

    // ...

}

または、エラーのみを報告する必要がある場合

if (response != null)
{
    int statusCode = (int)response.StatusCode;

    // 1xx-3xx are no real errors, while 3xx may indicate a miss configuration; 
    // 9xx are not common but sometimes used for internal purposes
    // so probably it is not wanted to show them to the user
    bool errorOccured = (statusCode >= 400);
    string friendlyStatusCode = "";

    if(errorOccured == true)
    {
        friendlyStatusCode = $"{ statusCode } ({ response.StatusCode })";
    }
    
    // ....
}
于 2020-06-07T09:05:15.667 に答える