[英]How to catch async void method exception?
我有一個這樣的實現:
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
,所以如果在匿名方法中引發異常,則實際上不會被RunRequest
的try
和catch
。
有什么建議如何重構嗎?
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
。
我在博客上有關於同步/異步委托的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.