How do I handle exceptions thrown by HttpClient (C#) methods?

In C#, exceptions thrown by HttpClient methods can be handled using try-catch blocks. The HttpClient class can throw exceptions for various reasons, such as network errors, DNS failures, server errors, timeouts, and other issues that can occur during an HTTP request.

Here's an example of how you can handle exceptions when using HttpClient:

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HttpClientExceptionExample
{
    public static async Task Main()
    {
        using (var httpClient = new HttpClient())
        {
            try
            {
                // Replace with the URL you want to call
                string url = "https://example.com/api/data";
                HttpResponseMessage response = await httpClient.GetAsync(url);

                // Ensure we got a successful response
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"Error: {response.StatusCode}");
                }
                else
                {
                    // Process the response content here
                    string content = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(content);
                }
            }
            catch (HttpRequestException e)
            {
                // Handle HttpRequestException (a subclass of IOException)
                Console.WriteLine($"Request error: {e.Message}");
            }
            catch (TaskCanceledException e)
            {
                // Handle timeouts (TaskCanceledException is thrown when the request times out)
                if (e.CancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("Request was canceled.");
                }
                else
                {
                    Console.WriteLine("Request timed out.");
                }
            }
            catch (Exception e)
            {
                // Handle other exceptions
                Console.WriteLine($"An error occurred: {e.Message}");
            }
        }
    }
}

In the code above:

  • We create a new instance of HttpClient.
  • We use HttpClient.GetAsync to send an HTTP GET request.
  • We wrap the call in a try-catch block to handle different types of exceptions:
    • HttpRequestException: This is thrown when an error occurs while sending the request or processing the response. For example, this can happen if the network is down, the server is unreachable, or the server returns a non-successful status code.
    • TaskCanceledException: This exception is thrown when the operation is canceled. It can also be thrown when a request times out. You can check if the operation was canceled due to a timeout by checking the CancellationToken.IsCancellationRequested property.
    • Exception: A general catch-all for any other exceptions that may occur.

When using HttpClient, it's also a good practice to handle the non-success status codes by checking HttpResponseMessage.IsSuccessStatusCode. This property returns true if the status code is in the range 200-299; otherwise, it returns false.

Please note that starting with C# 5.0, you should always make your network calls asynchronously (using async and await) to avoid blocking the calling thread, which can lead to poor application performance.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon