在 try catch 块中重试异常

面无表情

我试图复制一个场景,如果捕获到异常,代码应该重新运行一定次数。

using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.MyMethod(5));
    }
}

public class MyClass
{
    public Test(){}

    public string MyMethod(int tryCount) {          
        while(tryCount > 0)
        {
            // some logic that returns the switchType
            // in this case i'm just manually setting it to 1       
            int switchType = 1;

            try {
                switch(switchType)
                {
                    case 1:
                        return "it worked!!!";
                    case 2:
                        break;
                }
            } catch (Exception e){
                if (--tryCount == 0) throw new Exception("Failed");
            }
        }

        return null;
    }
}

我如何强制它进入 catch 块,以便我可以测试我的重试逻辑是否有效?

格雷格·赫兹

您的问题的最短答案是“只是抛出一个新的异常”。

但您可能也希望能够测试 Happy Path。

这是我要做的:

using System;
using System.Threading;

public class Program
{
    public static void Main()
    {
        // what happens when no problem
        MyClass.happyPath = true;
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.MyMethod(5));

        // does the retry work?
        MyClass.happyPath = false;
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.MyMethod(5));
    }
}

public class MyClass
{

    public static boolean happyPath = true; 

    public Test(){}

    public string MyMethod(int tryCount) {          
        while(tryCount > 0)
        {
            // some logic that returns the switchType
            // in this case i'm just manually setting it to 1       
            int switchType = 1;

            try {
                switch(switchType)
                {
                    case 1:

                        if (!happyPath) {
                           throw new Exception ("Oops, it didn't work!");
                        }
                        return "it worked!!!";
            case 2:
                        break;
                }
            } catch (Exception e){
                if (--tryCount == 0) throw new Exception("Failed");
            }
        }

        return null;
    }

}

throw你的break语句应该由你的被捕获内添加catch,它允许你检查你的重试逻辑。建议您添加一些日志记录。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章