如何避免异常捕获.NET中的复制粘贴

Bud*_*dda 7 .net asp.net copy-paste exception

使用.NET框架我有一个带有一组方法的服务,可以生成几种类型的异常:MyException2,MyExc1,Exception ...为了为所有方法提供适当的工作,每个方法都包含以下部分:

[WebMethod]
void Method1(...)
{
    try
    {
        ... required functionality
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
    ... process and return result if necessary
}
Run Code Online (Sandbox Code Playgroud)

在EACH服务方法中具有完全相同的东西是非常无聊的(每个方法具有不同的参数集),具有完全相同的异常处理功能......

有没有可能"分组"这些捕获部分并只使用一行(类似于C++宏)?.NET 4.0中的新功能可能与此主题有关吗?

谢谢.

PS欢迎任何想法.

Ree*_*sey 6

如果异常处理在所有方法中完全相同,则可以执行以下操作:

void CallService(Action method)
{
    try
    {
        // Execute method
        method();
    }
    catch(MyException2 exc)
    {
        ... process exception of MyException2 type
    }
    catch(MyExc1 exc)
    {   
        ... process exception of MyExc1 type
    }
    catch(Exception exc)
    {
        ... process exception of Exception type
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以重写您的客户端代码:

int i = 3;
string arg = "Foo";
this.CallService( () => this.Method1(i) );
this.CallService( () => this.Method2(arg, 5) );
Run Code Online (Sandbox Code Playgroud)

这允许您的Method1和Method2方法简单:

void Method1(int arg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}

void Method2(string stringArg, int intArg)
{
    // Leave out exception handling here...
    ... required functionality  
    ... process and return result if necessary
}
Run Code Online (Sandbox Code Playgroud)


dcp*_*dcp 5

为什么不将代码分解为辅助方法来为您执行此操作(您可以在将来添加所需的任何新异常HandleException,这使其具有可扩展性)?

try
{
    ... required functionality
}
catch (Exception e)
{
    HandleException(e);
    throw; // only if you need the exception to propagate to caller
}


private void HandleException(Exception e)
{
    if (e is MyException2)
    {
        ... process exception of MyException2 type
    }
    else if (e is MyExc1)
    {
        ... process exception of MyExc1 type
    }
    else
    {
        ... process exception of Exception type
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @chilltemp - 来吧,不要重复你的自我规则有更高的优先权. (3认同)