Dot-Net

如何避免異常擷取 .NET 中的複制粘貼

  • June 17, 2010

使用 .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
}

在每個服務方法中擁有完全相同的東西(每個方法都有不同的參數集)具有完全相同的異常處理功能是非常無聊的……

是否有可能將這些擷取部分“分組”並僅使用一行(類似於 C++ 宏)?.NET 4.0 中的一些新內容可能與此主題相關?

謝謝。

PS 歡迎任何想法。

如果所有方法中的異常處理完全相同,則可以執行以下操作:

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
   }
}

然後,您可以重寫您的客戶端程式碼來執行以下操作:

int i = 3;
string arg = "Foo";
this.CallService( () => this.Method1(i) );
this.CallService( () => this.Method2(arg, 5) );

這使您的 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
}

引用自:https://stackoverflow.com/questions/3064463