0

I have this method called Foo() that has a couple of API calls in its implementation:

Foo(){
    string resA, resB, resC;
    try{
        resA= APICall_A();
        resB= APICall_B();
        resC = APICall_C();
        someOperation(resB);
    }
     // Catches any exception thrown by any API Call
     catch(Exception ex){
        throw new Exception("API Call failed", ex)
    }
}

How could I implement a clean retry logic on the APICall_B() ONLY if it throws an exception where Exception.HResult = 0x8007001F? Changing the catch block to something like:

catch(Exception ex){
    if(ex.HResult == 0x8007001F){
        resB = APICall_B();
        resC = APICall_C();
        someOperation(resB);
    }
    else{
        throw new Exception("API Call failed", ex);
    }
}

Seems like such a waste of code. Wondering if there's a better way to do this.

Stefan
  • 17,448
  • 11
  • 60
  • 79
avhhh
  • 229
  • 1
  • 3
  • 11
  • [Polly](https://github.com/App-vNext/Polly) can handle retries, amongst other things, and is highly configurable. – John H Oct 05 '20 at 22:18
  • How many retries would you like? – Enigmativity Oct 05 '20 at 22:21
  • @Enigmativity I only want it to retry once. – avhhh Oct 05 '20 at 22:21
  • "Best" way is too broad. You need to provide a _specific_ question. See duplicate for broad advice about handling retry generally. If you only want to retry on a specific call, then you should wrap _only that specific call_ in retry logic. I will note the above code is confusing because you apparently are _assuming_ that only `APICall_B()` can throw an exception with that code, which doesn't seem like a valid or reasonable assumption _generally_. Maybe it holds in your case, but regardless you should only retry the operation you want to retry. – Peter Duniho Oct 05 '20 at 22:31
  • If this is the only place in your code where you want to do this then try not to think too much about it, and just make it work. I would just isolate the calls to `APICall_B` so that the rest of the code is not repeated. Keep it [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). – Dialecticus Oct 05 '20 at 22:32

1 Answers1

-1
  1. You can wrap every api call on a try catch block and catch exeptions of every one separaterly to do what you want.
  2. You can wrap every api call on separates methods to get the same result as above but in a more organized way.
  3. You can try Polly extensions package to treat some exceptions you configure and still keep the code as it is.
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
MestreDosMagros
  • 1,000
  • 5
  • 19