pm100
pm100

Reputation: 50190

http clients that dont throw on error

I am looking for c# HTTP client that doesn't throw when it gets an HTTP error (404 for example). This is not just a style issue; its perfectly valid for a non 2xx reply to have a body but I cant get at it if the HTTP stack throws when doing a GetResponse()

Upvotes: 4

Views: 2789

Answers (3)

Darrel Miller
Darrel Miller

Reputation: 142074

All the System.Net.Http.HTTPClient methods that return Task<HttpResponseMessage> do NOT throw on any HttpStatusCode. They only throw on timeouts, cancellations or inability to connect to a gateway.

Upvotes: 9

Pete Garafano
Pete Garafano

Reputation: 4913

If you are using the HttpClient in System.Net.Http, you can do something like this:

using (var client = new HttpClient())
using (var response = await client.SendAsync(request))
{
    if (response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStreamAsync();
        // You can do whatever you want with the resulting stream, or you can ReadAsStringAsync, or just remove "Async" to use the blocking methods.
    }
    else
    {
        var statusCode = response.StatusCode;
        // You can do some stuff with the status code to decide what to do.
    }
}

Since almost all methods on HttpClient are thread safe, I suggest you actually create a static client to use elsewhere in your code, that way you aren't wasting memory if you make a lot of requests by constantly creating a destroying clients for just one request when they can make thousands.

Upvotes: 3

rulebot
rulebot

Reputation: 232

What about implementing a class that is wrapping the HttpClient?

Let it implement the desired methods which are delegated to the client object and try/catch the exceptions in these delegating methods.

class MyClient 
{
    HttpClient client;

    [...]

    public String WrappedMethodA() 
    {
        try {
           return client.MethodA();
        } catch(Exception x) {
           return ""; // or do some other stuff.
        }
    }
}

After implementing your own client, you'll get rid of these exceptions.

If you need a HttpClient instance, inherit from HttpClient and override it's methods it like this:

    public String WrappedMethodA() 
    {
        try {
           return base.MethodA(); // using 'base' as the client object.
        } catch(Exception x) {
           return ""; // or do some other stuff.
        }
    }

Upvotes: -2

Related Questions