我有以下示例:(另请阅读代码中的注释,因为它会更有意义)
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
}
让我们假设PostAsync
的方法 _mySender
看起来像这样:
public Task<Task<Result>> PostAsync()
{
Task<Result> result = GetSomeTask();
return result;
}
问题是:
因为我不等待实际的Result
in the MyAsyncMethod
and if PostAsync
方法抛出异常,在什么上下文中抛出并处理异常?
and
有什么方法可以处理程序集中的异常吗?
让我惊讶的是,当我尝试改变时MyAsyncMethod
to:
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;
}