我在 C# 代码中进行了大量 Web API 调用。我不知道如何捕获错误。假设,互联网连接无法正常工作,那么我的代码显示运行时错误。如何正确地将它们放入 try catch 块中,一般规则是什么。我找到的所有文章都是关于如何抛出错误和错误消息。
API 调用示例:
WebResponse webResponse = webRequest.GetResponse();
string res = webResponse.ToString();
还有
using (var client = new HttpClient())
client.BaseAddress = new Uri(CairoBaseUrl);
var getStringTask = client.GetStringAsync(requestUrl);
response = await getStringTask;
还有,
HttpResponseMessage response = await client.PostAsync(
url,requestContent);
如果您正在调用 asp.net web api,我建议您使用为此目的而完成的 HttpClient
try
{
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
这是来自 MSDN 的示例,如何使用 http 客户端处理异常
在你的例子中你有
using (var client = new HttpClient())
client.BaseAddress = new Uri(CairoBaseUrl);
var getStringTask = client.GetStringAsync(requestUrl);
response = await getStringTask;
但是它不会工作,因为await运算符只能与标记为异步的方法一起使用,所以它应该是
var getStringTask = await client.GetStringAsync(requestUrl);