Good suggestion to implement a retry logic of a single step in C#?

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.

c#
.net
asked on Stack Overflow Oct 5, 2020 by avhhh • edited Oct 5, 2020 by Stefan

1 Answer

-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.
answered on Stack Overflow Oct 5, 2020 by MestreDosMagros • edited Oct 5, 2020 by Enigmativity

User contributions licensed under CC BY-SA 3.0