public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
// in real-life case this returns to a different assembly which I can't change
// but I need to do some exception handling on the Result in here
}
假设_mySender
的PostAsync
方法如下:
public Task<Task<Result>> PostAsync()
{
Task<Result> result = GetSomeTask();
return result;
}
问题是:
由于我在MyAsyncMethod
中不等待实际的Result
,如果PostAsync
方法抛出异常,异常会在哪个上下文中被抛出和处理?
以及
我是否有办法在我的程序集中处理异常?
当我尝试将MyAsyncMethod
更改为以下内容时,我感到惊讶:
public async Task<Task<Result>> MyAsyncMethod()
{
try
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
}
catch (MyCustomException ex)
{
}
}
即使没有等待实际结果,异常在这里被捕获。发生这种情况是因为 PostAsync
的结果已经可用,并且异常是在此上下文中抛出的,对吗?
是否可以使用 ContinueWith
处理当前类中的异常?例如:
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
var exceptionHandlingTask = resultTask.ContinueWith(t => { handle(t.Exception)}, TaskContinuationOptions.OnlyOnFaulted);
return resultTask;
}