我有以下代码(经过简化以进行此重现)。显然,catch 异常 block 将包含更多逻辑。
我有以下代码:
void Main()
{
var result = ExecuteAction(async() =>
{
// Will contain real async code in production
throw new ApplicationException("Triggered exception");
}
);
}
public virtual TResult ExecuteAction<TResult>(Func<TResult> func, object state = null)
{
try
{
return func();
}
catch (Exception ex)
{
// This part is never executed !
Console.WriteLine($"Exception caught with error {ex.Message}");
return default(TResult);
}
}
为什么 catch 异常 block 从未执行过?
最佳答案
没有抛出异常是因为func的实际签名是Funk<Task>
由于方法是异步的。
异步方法有特殊的错误处理,直到你 await 函数才会引发异常。如果你想支持异步方法,你需要有第二个函数来处理异步委托(delegate)。
void Main()
{
//This var will be a Task<TResult>
var resultTask = ExecuteActionAsync(async() => //This will likely not compile because there
// is no return type for TResult to be.
{
// Will contain real async code in production
throw new ApplicationException("Triggered exception");
}
);
//I am only using .Result here becuse we are in Main(),
// if this had been any other function I would have used await.
var result = resultTask.Result;
}
public virtual async TResult ExecuteActionAsync<TResult>(Func<Task<TResult>> func, object state = null)
{
try
{
return await func().ConfigureAwait(false); //Now func will raise the exception.
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught with error {ex.Message}");
return default(TResult);
}
}
关于c# - 来自 Func<> 的异常未被捕获(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133605/