Reducing duplicate error handling code in C#?

后端 未结 4 1325
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 19:08

I\'ve never been completely happy with the way exception handling works, there\'s a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to

4条回答
  •  臣服心动
    2020-12-29 19:27

    Here's what I did recently. It has probably been done elsewhere better, but it seems pretty clean and reusable.

    I have a utility method that looks like this:

        public delegate void WorkMethod();
    
        static public void DoAndRetry(WorkMethod wm, int maxRetries)
        {
            int curRetries = 0;
            do
            {
                try
                {
                    wm.Invoke();
                    return;
                }
                catch (Exception e)
                {
                    curRetries++;
                    if (curRetries > maxRetries)
                    {
                        throw new Exception("Maximum retries reached", e);
                    }
                }
            } while (true);
        }
    

    Then in my application, I use c#'s Lamda expression syntax to keep things tidy:

    Utility.DoAndRetry( () => ie.GoTo(url), 5);
    

    This calls my method and retries up to 5 times. At the fifth attempt, the original exception is rethrown inside of a retry exception.

提交回复
热议问题