这是我的HttpService类,它运行正常。但它看起来很奇怪,每个函数中的代码都大致相同。我应该在每个函数中编写try / catch,特别是TaskCanceledException,如果我没有在这里捕获它,我的应用程序将终止。有人可以给我一些关于如何优化代码的例子吗?
[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;
}
}
答案 0 :(得分:5)
不,这根本不是真的;它是调用的代码它也有机会(实际上是责任)来处理错误。例如:如果我在这里没有抓到它,我的申请将会终止。
try {
var permission = await getPermission();
//...
} catch(Exception ex) {
// log, whatever
}
将异常处理放在最合适的位置可以减少async
方法中不必要的代码。您当前正在做的是让您的async
方法假装没有发生任何不良事件 - 这不是最佳做法。
答案 1 :(得分:3)
免责声明:我无法编译,因此您可能需要按摩它。
我看到你唯一能做的就是制作一个这样的方法:
public async Task<T> getAsync(string url)
{
try
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsAsync<T>();
return (T)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<User>> getUsers()
{
return await getAsync("api/User");
}
public async Task<IEnumerable<permission>> getPermission()
{
return await getAsync("api/User");
}
public async Task<CurrentUser> getCurrentUserInfo(User user)
{
return await getAsync("api/User?name=" + user.Name);
}