2017-04-03 2 views
0

CancellationTokenが59秒のタスクでデータベースクエリが実行されます。タスクがキャンセルされると、TaskCanceledExceptionがスローされます。しかし、この例外はAggregateExceptionの一部としてキャッチされます。 特定のエラーメッセージを提供したいと思います。したがって、AggregateExceptionの実際の例外がTaskCancelationExceptionである場合、コード内で検証することは可能ですか?AggregateExceptionに含まれる実際の例外タイプを取得します。

+0

'await'はAggregateExceptionをアンラップと' InnerExceptions' –

+0

は、[クラスのドキュメント](https://msdn.microsoft.com/enを確認の最初をスローします-us/library/system.aggregateexception(v = vs.110).aspx)。内部例外にアクセスする方法、複数の集約例外を1つに平坦化する方法、またはすべての内部例外を処理するために 'Handle'を使用する方法を示します –

答えて

2

あなたの状況に応じて、InnerExceptionまたはInnerExceptionsを使用する必要があります。

if (x.InnerException is TaskCanceledException) 
{ 
    // ... 
} 

1つの例外のみがあることがわかっている場合は、上記のように動作します。

 catch (AggregateException ae) 
     { 
      if (ae.InnerException is TaskCanceledException) 
      { 
       LoggerService.Log(LogLevel.Error, "GetReport Request was cancelled"); 
       throw ae.InnerException; 
      } 

      LoggerService.Log(LogLevel.Error, string.Format("GetReport Request failed: {0}", ae.InnerException.Message)); 
      throw; 
     } 

をしかし例外の後の上にスローされます。

var sb = new StringBuilder(); 

foreach (var inner in x.InnerExceptions) 
{ 
    sb.AppendLine(inner.ToString()); 
} 

System.Diagnostics.Debug.Print(sb.ToString()); 
3

あなたは例外のリストを取得するか、一つだけがある場合は最初のものを使用することができます。

var first = agg.InnerException; // just the first 

foreach (Exception ex in agg.InnerExceptions) // iterate over all 
{ 
    // do something with each and every one 
} 
0

のInnerExceptionの種類をチェック働いた:あなたは複数を持っている場合しかし、あなたはそれらのすべてで何かをしたいですWCF通信はAggregateExceptionにカプセル化されます。 何らかの理由で、2番目の例外タイプを読み取るメカニズムが簡単ではありません。しかし、次のようにそれが働いている:

   catch (AggregateException ae) 
       { 
        endMessage = string.Format("Defined Query failed. Error: {0}", ae.Message); 

        // Set specific error message when TaskCanceledException is contained in AggregateException 
        var fe = ae.InnerException as FaultException<ExceptionDetail>; 
        if (fe != null) if (Type.GetType(fe.Detail.Type) == typeof(TaskCanceledException)) endMessage = "Defined Query was cancelled"; 

        logLevel = LogLevel.Error; 
        messageType = MessageType.Error; 
       } 
関連する問題