如何捕获异步void方法异常?

时间:2017-01-19 13:22:17

标签: c# async-await

我有这样的实现:

Task<IEnumerable<Item1>> GetItems1() 
{
    return RunRequest(async () => ParseItemsFromResponse(await(httpClient.Get(..))));
}

Task<IEnumerable<Item2>> GetItems2() 
{
    return RunRequest(async () => ParseItemsFromResponse(await httpClient.Get(..)));
}


TResult RunRequest<TResult>(Func<TResult> req)
{
    try
    {
        return req();
    }
    catch (Exception ex)
    {
        // Parse exception here and throw custom exceptions
    }
}

问题是无效的匿名方法async () => ParseItemsFromResponse(..)

由于它返回void而不是Task,如果在匿名方法中抛出异常,它实际上不会被try和{catch捕获{1}}中的{1}}。

有关如何重构此内容的任何建议吗?

1 个答案:

答案 0 :(得分:3)

RunRequest应该采用Func<Task<TResult>>,因此:

async Task<TResult> RunRequestAsync<TResult>(Func<Task<TResult>> req)
{
  try
  {
    return await req().ConfigureAwait(false);
  }
  catch (Exception ex)
  {
    // Parse exception here and throw custom exceptions
  }
}

然后,您的async lambda将转换为async Task<T>方法,而不是async void

我在博客上有关于sync/async delegates的更多信息。