c# - 关于在 C# 中制作可重用的 try/catch block 的建议?

标签 c# .net exception-handling try-catch

我有一个类,其中包含大约 20 多个方法。每个都进行一些 Web 服务消息处理。我只需要对其进行更改,并意识到这些方法中的每一个都有完全相同的 try/catch:

        try
        {
            /* *** actual processing specific to each method goes here *** */
        }
        catch (FaultException<CustomException> cfex)
        {
            // common stuff
        }
        catch (CustomException cfex)
        {
            // common stuff
        }
        catch (Exception ex)
        {
            // common stuff
        }
        finally
        {
            FinalizeServiceCall(wsBus, wsMessage, response, logProps);
        }

我的问题是;不是在每个方法中都使用完全相同的 try/catch block ,有没有办法让它变得通用?我的想法是 .NET 有类似 TransactionScope 的东西,它以某种方式检测离开该 block 时是否发生异常。我是否可以利用类似的东西来制作一个通用的 try/catch block ?还有其他想法吗?

最佳答案

我会这样做:

创建一个包含 try/catch 的方法并将 Action 传递给它并在 try 部分执行该操作:

public void Method1()
{
    Action action = () =>
    {
        // actual processing of Method 1
    };
    SafeExecutor(action);
}

public void Method1b()
{
    SafeExecutor(() =>
    {
        // actual processing of Method 1
    });
}

public void Method2(int someParameter)
{
    Action action = () =>
    {
        // actual processing of Method 2 with supplied parameter
        if(someParameter == 1)
        ...
    };
    SafeExecutor(action);
}

public int Method3(int someParameter)
{
    Func<int> action = () =>
    {
        // actual processing of Method 3 with supplied parameter
        if(someParameter == 1)
            return 10;
        return 0;
    };
    return SafeExecutor(action);
}

private void SafeExecutor(Action action)
{
    SafeExecutor(() => { action(); return 0; });
}

private T SafeExecutor<T>(Func<T> action)
{
    try
    {
        return action();
    }
    catch (FaultException<CustomException> cfex)
    {
        // common stuff
    }
    catch (CustomException cfex)
    {
        // common stuff
    }
    catch (Exception ex)
    {
        // common stuff
    }
    finally
    {
        FinalizeServiceCall(wsBus, wsMessage, response, logProps);
    }

    return default(T);
}

SafeExecutor 的两个版本让您可以处理有和没有返回类型的方法。
Method1b 显示您的方法中不需要变量 action,如果您认为这样更易读,可以将其内联。

关于c# - 关于在 C# 中制作可重用的 try/catch block 的建议?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6046382/

相关文章:

c# - Outlook ItemAdd 事件针对新日历项目触发两次

c# - 用于 .Net C# 应用程序的 SharpZipLib 替代品

.net - 如何确定项目使用的是哪个 .net 单元测试框架?

c++ - 在 C++ 中捕获段错误或任何其他错误/异常/信号,就像在 Java 中捕获异常一样

c++ - 捕获并修改 std::exception 和子类,重新抛出相同类型

python - 识别python中的特定异常

c# - 如何检查对象是否是某种类型的数组?

c# - 从 C# 调用 C++ 函数并将数据发送回 C#

c# - 如何从用属性修饰的 C# 类生成 .proto 文件?

单元测试期间的 C# 扩展方法奇怪