I have some logic for Task
and Task<T>
.
Is there any way to avoid duplicating code ?
My current code is following:
public async Task<SocialNetworkUserInfo> GetMe()
{
return await WrapException(() => new SocialNetworkUserInfo());
}
public async Task AuthenticateAsync()
{
await WrapException(() => _facebook.Authenticate());
}
public async Task<T> WrapException<T>(Func<Task<T>> task)
{
try
{
return await task();
}
catch (FacebookNoInternetException ex)
{
throw new NoResponseException(ex.Message, ex, true);
}
catch (FacebookException ex)
{
throw new SocialNetworkException("Social network call failed", ex);
}
}
public async Task WrapException(Func<Task> task)
{
try
{
await task();
}
catch (FacebookNoInternetException ex)
{
throw new NoResponseException(ex.Message, ex, true);
}
catch (FacebookException ex)
{
throw new SocialNetworkException("Social network call failed", ex);
}
}
You can make the Task
overload call the other one, and return a dummy value.
public async Task WrapException(Func<Task> task)
{
await WrapException<object>(async () => {
await task();
return null;
});
}
Or, since the async
keyword is unnecessary here:
public Task WrapException(Func<Task> task)
{
return WrapException<object>(async () => {
await task();
return null;
});
}
Assuming that Func
does not itself throw, the following would work.
public async Task<T> WrapException<T>(Func<Task<T>> task)
{
var actualTask = task();
await WrapException((Task)actualTask);
return actualTask.Result;
}
We know that Result
won't block or throw since WrapException
ensured it ran to completion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With