Asynchronous operations and AggregateException: retain exception information
When waiting for a task that has failed, await
usually rethrows the stored exception. However, if the stored exception is AggregateException
, it will just rethrow the first exception.
To overcome this issue and catch all error messages, consider the following best practices:
Use extension methods
You can create an extension method WithAggregateException
which preserves the original exception stack trace if present:
<code class="language-csharp">public static async Task WithAggregateException(this Task source) { try { await source.ConfigureAwait(false); } catch { // 检查取消的任务。 if (source.Exception == null) throw; // 保留原始堆栈跟踪。 ExceptionDispatchInfo.Capture(source.Exception).Throw(); } }</code>
By using this extension method you can wait for tasks and handle AggregateException
as a single entity with retained details.
Example
Consider the following example:
<code class="language-csharp">// 创建一个具有多个异常的任务。 var task = Task.FromException(new AggregateException(new Exception("异常 1"), new Exception("异常 2"))); // 使用扩展方法等待任务。 try { await task.WithAggregateException(); } catch (AggregateException ex) { Console.WriteLine("捕获所有异常:"); foreach (var innerEx in ex.InnerExceptions) { Console.WriteLine(innerEx.Message); } }</code>
Output:
<code>捕获所有异常: 异常 1 异常 2</code>
This extension method allows you to retain all exception information while waiting for the task, ensuring that error details are not accidentally lost.
The above is the detailed content of How Can I Preserve All Exception Details When Awaiting a Task with AggregateException?. For more information, please follow other related articles on the PHP Chinese website!