-1

I am developing one application and in that I need to consume Rest API which has token associated with it. After specific interval that token get's expired so in that case suppose if I try to call that API it's throwing exception. So to resolve this should I refresh the token in catch block and use GoTo to execute the try block again. I read couple of articles and most of them suggest to avoid using GoTo.

Below are the links which I refer for best approach to follow but still am not convinced whether to go with it or not:

1> Is it possible to execute the code in the try block again after an exception in caught in catch block?

2> https://blogs.msdn.microsoft.com/abhinaba/2005/10/01/c-try-and-retry/

Dishant
  • 1,545
  • 12
  • 29
  • This question is primarily opinion-based I'm afraid, which makes it off topic here. However, there are libraries that will help with this. If you can justify going to .NET Core 2.1 which will be released properly in a few weeks the [HTTP factory](https://blogs.msdn.microsoft.com/webdev/2018/02/28/asp-net-core-2-1-preview1-introducing-httpclient-factory/) object in there gives retry logic. Otherwise, you should take a look at [Polly](http://www.thepollyproject.org) which is an open source library (now part of the [.NET Foundation](https://dotnetfoundation.org)) for exactly this purpose. – DavidG May 09 '18 at 11:10
  • What kind of token is this? JWT or something that has an expiration time that you can access? I ask because I would not base my retry logic, or any non-exceptional occurrence, on an exception. – Crowcoder May 09 '18 at 11:10
  • 2
    Oh, and *never* use `goto`! – DavidG May 09 '18 at 11:10
  • Take a piece of paper and figure it out. It is much simpler when you look at the problem that way. – FCin May 09 '18 at 11:15
  • @Crowcoder, I am not sure with JWT but I get access token after successful login which I have to pass with each request then after. That token has a time limit so after that time limit it will get expired and calling the API will throw 401 Unauthorized exception. – Dishant May 09 '18 at 11:55
  • Why down vote? I know how to deal with the issue, but I asked this question because I want to know the best approach which I can follow. – Dishant May 09 '18 at 11:57
  • Best practice questions are off topic here, that's likely the reason you were downvoted. – DavidG May 09 '18 at 11:59

3 Answers3

0

Just put a retry count and a continue to skip to the next iteration of a loop in your logic:

 int maxRetry = 10;
        for (int i = 0; i<=maxRetry; i++)
        {
            try
            {
                //DO YOUR STUFF
            }
            catch (Exception)
            {
                //OH NOES! ERROR!
                continue; //RETRY!
            }
        }

When it has tried 10 times it exits and that's it.

You can unleash your fantasy with any loop you like for, while, do while etc. Use the one that fits your needs.

If there is some really bad error that needs to stop the execution of the loop then break then throw an exception and use

  catch(VeryWrongException ex)
  {
      throw;
  } 
  catch (Exception)
  {
       //OH NOES! ERROR!
       continue; //RETRY!
  }

where VeryWrongException is the type of exceptions you want to actually manage, instead of using the previous catch condition.

Extra: To have an idea of what kind of exceptions your code can generate and catch them, use intellisense, it's your friend:

intellisense

Liquid Core
  • 1
  • 6
  • 27
  • 52
-1

Catch statements which use GoTo to retry the same logic can be dangerous if they are not used properly.

A better way of dealing with this is to write some retry logic, that will attempt to perform your tasks a limited number of times, ideally allowing you to specify your exception.

If you don't want to write your own retry logic, I can recommend you use an external library such as Polly

An Example of its usage would be this :

// Set up the policy
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetry(
    3,
    retryAttempt => TimeSpan.FromSeconds(5 * retryAttempt)
    );

// Attempt to send the message, use Polly to retry a maximum of three times.
retryPolicy.Execute(() =>
{
    // Your Code
});
Adzy_12
  • 58
  • 2
  • 9
-1

I am afraid you are trying to solve this problem at the wrong place. If you request to an API fails, because of an expired token, you should just throw an exception.

Another class, maybe the one that is responsible for initiating the request in the first place, could resolve the error (refreshing the token) and retry requesting data.

If you merge all this responsibility in one place, things could get complicated really fast.

Wim Haanstra
  • 5,918
  • 5
  • 41
  • 57