可以';t捕获从任务引发的异常

本文关键字:任务 异常 可以 | 更新日期: 2023-09-27 18:25:48

我已经为此挠头一段时间了。我不知道这个异常是从哪里抛出的。我到底该在哪里发现这个异常?它是System.Net.WebException。我想我只是没有得到Task和async/await。我知道我正在创建其他线程,这很好,但我在哪里处理异常?

The remote server returned an error: (403) Forbidden.

这是代码:

public async void sendRequest(string database, string table, string where, bool isPost, int deviceType)
{
    string urlQuery = Constants.URL_QUERY + database + "/" + table + "?" + where;
    Debug.WriteLine("URL Query: " + urlQuery);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlQuery);
    request.Method = isPost ? "POST" : "GET";
    request.ContentType = "application/json";
    try
    {
        Debug.WriteLine("getting response");
        WebResponse response = await makeAsyncRequest(request);
        Debug.WriteLine("response obtained");
        finishRequest(response);
    }
    catch (WebException e)
    {
        Debug.WriteLine("WebException caught");
    }
}
private async static Task<WebResponse> makeAsyncRequest(HttpWebRequest req)
{
    Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(req.BeginGetResponse, req.EndGetResponse, null);
    await task.ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            Debug.WriteLine("It's faulted.");
            t.Exception.Handle((x) =>
            {
                if (x is WebException)
                {
                    Debug.WriteLine("It's a web exception");
                    return true;
                }
                Debug.WriteLine("Exception?: " + x);
                return false;
            });
        }
    });
    Debug.WriteLine("returning task");
    return task.Result;
}
private static void finishRequest(WebResponse response)
{
    Debug.WriteLine("finishRequest called");
}

以下是我在输出窗口中看到的内容:

2014-10-07 14:05:05.104 FormsTemplateiOS[1568:53280] getting response
[0:] getting response
Thread started:  #3
Thread started: <Thread Pool> #4
Thread started: <Thread Pool> #5
Thread started: <Thread Pool> #6
Thread started: <Thread Pool> #7
Thread started:  #8
[0:] 
2014-10-07 14:05:05.681 FormsTemplateiOS[1568:53326] It's faulted.
[0:] It's faulted.
[0:] 
2014-10-07 14:05:05.804 FormsTemplateiOS[1568:53326] It's a web exception
[0:] It's a web exception
Unhandled Exception:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
Unhandled Exception:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
  at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x0033b] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.0.0.63/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1718 
  at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00165] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.0.0.63/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1485 
The program 'Mono' has exited with code 0 (0x0).
Debugging session ended.

编辑:

我根据Stephen Cleary的建议更新了makeAsyncRequest(HttpWebRequest)。我仍然有同样的问题。

private async static Task<WebResponse> makeAsyncRequest(HttpWebRequest req)
{
    Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(req.BeginGetResponse, req.EndGetResponse, null);
    try
    {
        return await task;
    }
    catch (WebException e)
    {
        Debug.WriteLine("It's a WebException");
    }
    catch (Exception e)
    {
        Debug.WriteLine("Other Exception");
    }
    return null;
}

输出窗口:

2014-10-07 14:32:08.385 FormsTemplateiOS[1588:57008] getting response
[0:] getting response
Thread started:  #3
Thread started: <Thread Pool> #4
Thread started: <Thread Pool> #5
Thread started: <Thread Pool> #6
Thread started: <Thread Pool> #7
Thread started:  #8
Unhandled Exception:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
Unhandled Exception:
System.Net.WebException: The remote server returned an error: (403) Forbidden.
  at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x0033b] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.0.0.63/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1718 
  at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00165] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.0.0.63/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1485 
The program 'Mono' has exited with code 0 (0x0).
Debugging session ended.

可以';t捕获从任务引发的异常

我知道我正在创建其他线程,这很好,所有

事实上没有。您可能想阅读我的async简介。

还有:

  • 避免async void
  • 使用await而不是ContinueWith

您可能还会发现我的async最佳实践文章很有帮助。

private async static Task<WebResponse> MakeRequestAsync(HttpWebRequest req)
{
  Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(req.BeginGetResponse, req.EndGetResponse, null);
  try
  {
    return await task;
  }
  catch (WebException ex)
  {
    Debug.WriteLine("It's a web exception");
  }
  catch (Exception ex)
  {
    Debug.WriteLine("It's not a web exception.");
  }
}

最后,请考虑使用HttpClient而不是HttpWebRequest。CCD_ 11是为CCD_。