简体   繁体   English

无法捕获Task引发的异常

[英]Can't catch Exception thrown from Task

I've been scratching my head on this for a while. 我已经为此抓了一段时间了。 I have no clue where this exception is being thrown. 我不知道在哪里抛出该异常。 Where the heck am I supposed to catch this exception? 我应该在哪里捕获此异常? It's a System.Net.WebException . 这是System.Net.WebException I guess I'm just not getting Task and async/await. 我想我只是没有得到Task和async / await。 I understand I'm creating other threads, which is great and all, but where do I handle the exception? 我知道我正在创建其他线程,这很重要,但是我应该在哪里处理异常?

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

Here is the code: 这是代码:

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");
}

Here is what I see in my Output window: 这是在“输出”窗口中看到的内容:

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.

Edit: 编辑:

I updated makeAsyncRequest(HttpWebRequest) per Stephen Cleary suggestion. 我根据Stephen Cleary的建议更新了makeAsyncRequest(HttpWebRequest) I'm still having the same problem. 我仍然有同样的问题。

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;
}

Output window: 输出窗口:

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.

I understand I'm creating other threads, which is great and all 我了解我正在创建其他线程,这很棒,所有

No, actually. 不,实际上。 You may want to read my async intro . 您可能需要阅读我的async介绍

Also: 也:

  • Avoid async void . 避免async void
  • Use await instead of ContinueWith . 使用await代替ContinueWith

You may also find my async best practices article helpful. 您可能还会发现我的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.");
  }
}

As a final note, consider using HttpClient instead of HttpWebRequest . 最后,请考虑使用HttpClient而不是HttpWebRequest HttpClient was designed for async usage. HttpClient是为async使用而设计的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM