Avoiding duplicate methods for task and task <T>

I have some logic for Task and Task<T> . Is there a way to avoid code duplication?

My current code is as follows:

 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); } } 
+6
source share
2 answers

You can make the Task overload different, and return a dummy value.

 public async Task WrapException(Func<Task> task) { await WrapException<object>(async () => { await task(); return null; }); } 

Or, since the async is not needed here:

 public Task WrapException(Func<Task> task) { return WrapException<object>(async () => { await task(); return null; }); } 
+2
source

Assuming Func doesn't throw away, the following will 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 will not block or throw, as a WrapException guaranteed that it ended.

+1
source

Source: https://habr.com/ru/post/970044/


All Articles