6

以下のこのメソッドで例外をキャッチするにはどうすればよいですか?

    private static Task<string> MakeAsyncRequest(string url)
    {
        if (!url.Contains("http"))
            url = "http://" + url;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        request.Method = "GET";
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;

        Task<WebResponse> task = Task.Factory.FromAsync(
        request.BeginGetResponse,
        asyncResult => request.EndGetResponse(asyncResult),
        (object)null);

        return task.ContinueWith(t => FinishWebRequest(t.Result));

    }

404、403などのエラーが発生する特定の場所は次のとおりです。

Task<WebResponse> task = Task.Factory.FromAsync(
            request.BeginGetResponse,
            asyncResult => request.EndGetResponse(asyncResult),
            (object)null);

それらを処理する方法がわかりません

4

2 に答える 2

13

あなたのエラーは、デリゲートの呼び出しで発生している可能性がありますrequest.EndGetResponse(asyncResult)

ただし、次を使用してタスクを作成できます。

Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

これにより、すべての例外がタスクに伝播されます。

ContinueWithデリゲートのエラーを確認できます。

return task.ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        //handle error
        Exception firstException = t.Exception.InnerExceptions.First();
    }
    else
    {
        return FinishWebRequest(t.Result);
    }
});

または、C#5 を使用している場合は、async/await を使用してMakeAsyncRequest. これにより、例外がアンラップさAggregateExceptionれます。

private static async Task<string> MakeAsyncRequest(string url)
{
    if (!url.Contains("http"))
        url = "http://" + url;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    request.Method = "GET";
    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    Task<WebResponse> task = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
    WebResponse response = await task;
    return FinishWebRequest(response);
}
于 2012-12-03T18:47:52.003 に答える
1

したがって、タスクの状態が Faulted 状態に変わり、このエラーをいくつかの方法で確認できます。

// Inside method MakeAsyncRequest
Task<WebResponse> task = Task.Factory.FromAsync(
    request.BeginGetResponse,
    asyncResult => request.EndGetResponse(asyncResult),
    (object)null);

// this 'task' object may fail and you should check it

return task.ContinueWith(
   t => 
     {
        if (t.Exception != null)
          FinishWebRequest(t.Result))

        // Not the best way to fault "continuation" task
        // but you can wrap this into your special exception
        // and add original exception as a inner exception
        throw t.Exception.InnerException;

        // throw CustomException("The request failed!", t.Exception.InnerException);
     };

いずれの場合でも、タスクが失敗する可能性があることを準備する必要があるため、同じ手法を使用して結果のタスクを処理する必要があります。

// outside method MakeAsyncRequest
var task = MakeAsyncRequest(string url);

task.ContinueWith(t => 
  // check tasks state or use TaskContinuationOption
  // handing error condition and result
);

try
{
  task.Wait(); // will throw
  Console.WriteLine(task.Result); // will throw as well
}
catch(AggregateException ae)
{
  // Note you should catch AggregateException instead of
  // original excpetion
  Console.WriteLine(ae.InnerException);
}
于 2012-12-03T18:59:52.640 に答える