我有一个通用类,用于在网络中执行CRUD操作。
a
我有一个自定义类,从那里可以调用网络服务。
public class RequestService:IRequest
{
public HttpClient GetClient()
{
string USERNAME = "XXXXXX";
string PASSWORD = "XXXXX";
string BASE_ADDRESS = "https://something.net/api/sync/";
var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{USERNAME}:{PASSWORD}")));
var client = new HttpClient
{
BaseAddress = new Uri(BASE_ADDRESS),
DefaultRequestHeaders = { Authorization = authValue }
};
return client;
}
public async Task<TResult> GetAsync<TResult>(HttpClient client, string url)
{
client.Timeout = TimeSpan.FromSeconds(30);
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var jsonString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TResult>(jsonString);
return result;
}
public async Task<string> GetStringAsync(HttpClient client, string url)
{
var httpRequest = new HttpRequestMessage(new HttpMethod("GET"), url);
var response = client.SendAsync(httpRequest).Result;
var jsonString = await response.Content.ReadAsStringAsync();
return jsonString;
}
public async Task<TResult> PostAsync<TRequest, TResult>(HttpClient client, TRequest t,string url)
{
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(url, httpContent);
response.EnsureSuccessStatusCode();
var jsonString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TResult>(jsonString);
return result;
}
}
在ViewModel中:
public class DeviceService:IDevice
{
private IRequest RequestService;
public DeviceService(IRequest request)
{
RequestService = request;
}
public async Task<int> GetDeviceID()
{
var client = RequestService.GetClient();
var id = await RequestService.PostAsync<Object, int>(client, null, "Registerdevice");
return id;
}
}
因此,当我拥有稳定的Internet或服务器的成功响应时,一切正常。现在,我想在代码中添加错误处理功能,包括:无互联网连接,其他网络异常和api错误处理,以便我可以将错误告知用户。我不确定该怎么做。我尝试在'RequestService'类中使用try-catch块并读取每个异常并抛出它,这意味着我必须在DeviceService类和ViewModel中添加try-catch块。还是我必须这样做?我不确定。