How can I improve this exception retry scenario?

前端 未结 10 1557
暗喜
暗喜 2020-12-13 19:39

I have a web service method I am calling which is 3rd party and outside of my domain. For some reason every now and again the web service fails with a gateway timeout. Its i

10条回答
  •  情话喂你
    2020-12-13 20:11

    You should use recursion (or a loop), and should only retry if you got the error you expected.

    For example:

    static void TryExecute(Action method, Func retryFilter, int maxRetries) where TException : Exception {
        try {
            method();
        } catch(TException ex) {
            if (maxRetries > 0 && retryFilter(ex))
                TryExecute(method, retryFilter, maxRetries - 1);
            else
                throw;
        }
    }
    

    EDIT: With a loop:

    static void TryExecute(Action method, Func retryFilter, int maxRetries) where TException : Exception {
        while (true) {
            try {
                method();
                return;
            } catch(TException ex) {
                if (maxRetries > 0 && retryFilter(ex))
                    maxRetries--;
                else
                    throw;
            }
        }
    }
    

    You can try to prevent future errors in retryFilter, perhaps by Thread.Sleep.

    If the last retry fails, this will throw the last exception.

提交回复
热议问题