Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change these codes to c# style? [closed]

This is my HttpService class, it works fine. But it seems weird, the code in every function much the same. And I should write try/catch in every functions, espcially TaskCanceledException, if I do not catch it here, my application will terminate. Could some one give me some example about how to optimize the code?

[Export(typeof(IDataSource))]
public class HttpService : IDataSource
{
    HttpClient client = new HttpClient();
    public HttpService()
    {
        client.BaseAddress = new Uri("https://localhost:3721");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public void Initialize(CurrentUser currentUser)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(Encoding.UTF8.GetBytes(currentUser.Name + ":" + currentUser.Password)));
    }

    public async Task<IEnumerable<User>> getUsers()
    {
        try
        {
            var response = await client.GetAsync("api/User");
            //response.EnsureSuccessStatusCode(); // Throw on error code.
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<IEnumerable<User>>();
                return result;
            }
            else
            {
                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

    public async Task<IEnumerable<permission>> getPermission()
    {
        try
        {
            var response = await client.GetAsync("api/User");
            //response.EnsureSuccessStatusCode(); // Throw on error code.
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<IEnumerable<permission>>();
                return result;
            }
            else
            {
                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

    public async Task<CurrentUser> getCurrentUserInfo(User user)
    {
        try
        {
            var response = await client.GetAsync("api/User?name=" + user.Name);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<CurrentUser>();
                return result;
            }
            else
            {

                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

}
like image 271
T_T Avatar asked Nov 29 '25 23:11

T_T


1 Answers

if I do not catch it here, my application will terminate.

no, that is simply not true; it is the code that invokes it also has the chance (and indeed, responsibility) to handle the errors. For example:

try {
    var permission = await getPermission();
    //...
} catch(Exception ex) {
    // log, whatever
}

Putting the exception handling in the most appropriate place will reduce this unnecessary code in your async methods. What you are currently doing is making your async methods pretend that nothing bad happened - that is not the best practice here.

like image 157
Marc Gravell Avatar answered Dec 02 '25 14:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!