A
A
Alexander Simonov2018-07-17 17:54:35
C++ / C#
Alexander Simonov, 2018-07-17 17:54:35

How to make a method call again?

Hello everyone, I have some code like this

public async Task<List<AccountListView>> GetAsync()
        {
            try
            {
                return await TryGetAccountListAsync();
            }
            catch (UnauthorizedException)
            {
                await Context.Renew();

                return await TryGetAccountListAsync();
            }
        }

        private async Task<List<Model>> TryGetAccountListAsync()
        { 
           var response = /*Запрос к серверу*/
           if(!response.IsSuccessStatusCode) {
               throw new UnauthorizedException(); 
            } eles { 
               return response.ToModel();
            }
         }

The bottom line is, we are trying to make a request, if we get something bad, then we throw an exception, if the exception is due to the fact that the token is outdated, then we try to update the token and repeat the request. How to make it more beautiful? For some reason, my method doesn’t work for me, because I already have 10 pairs of these and it somehow doesn’t warm my soul

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
basrach, 2018-07-17
@SimasikS

If you want "clear and beautiful so that it's no worse than the boys", take a look at the Polly lib :

public async Task<List<AccountListView>> GetAsync()
{
  var policy = Policy
    .Handle<UnauthorizedException>()
    .RetryAsync(
      retryCount: 1,
      onRetryAsync: (e, i) => Context.Renew());

  return await policy.ExecuteAsync(TryGetAccountListAsync);
}

Created policycan be reused. Those. you don’t have to copy-paste anymore, just declare one policy per application, and then just call what requires updating the token through this policy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question