How to catch async void method exception?

旧街凉风 提交于 2020-01-15 05:27:06

问题


I have an implementation like this:

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
    }
}

The issue is the void anonymous method async () => ParseItemsFromResponse(..).

Since it returns void and not a Task, if there's an exception thrown within the anonymous method, it's actually not going to be caught by the try and catch within the RunRequest.

Any suggestions how to refactor this?


回答1:


RunRequest should take a Func<Task<TResult>>, as such:

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
  }
}

Then your async lambdas are converted to async Task<T> methods instead of async void.

I have more information on sync/async delegates on my blog.



来源:https://stackoverflow.com/questions/41742853/how-to-catch-async-void-method-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!