HttpClient, what are the best practices for handling exceptions?


#1

I am writing methods to use HttpClient more easily and handle the exceptions of Get, Post, etc. This is my current code. I am not satisfied with my code and I am looking for a design pattern to improve it. Any suggestions?

public static async Task<HttpResponseMessage> TryGetAsync(this HttpClient client, string path)
{
    try
    {
        return await client.GetAsync(path);
    }
    catch(Exception ex)
    {
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
}

#2

The flaw I see is that you’re ignoring the exception and just return a generic error instead. Thus, you have no way of knowing why the code fails if it does fail. In general, you should do "something"with the exception, like writing it to a log file or make it part of the response message.
A generic design pattern is basically to add logging… :wink:

Also, your code is synchronizing an asynchronous function. Instead of calling it ‘TryGetAsync’ you could just call it ‘Get’ as that’s basically is what you’re doing here. And yes, the ‘async’ still needs to be in front of the method, but it’s synchronizing an asynchronous call. So, use the more logical name as ‘TryGetAsync’ makes it sound asynchronous…


.NET Foundation Website | Blog | Projects | Code of Conduct