2013-02-16 22 views
1

我有一個網站,我需要對WCF服務進行異步調用。 我想在try-catch塊中包裝每個調用,以便處理TimeoutExceptions和CommunicationExceptions。如何在try-catch塊中包裝每個WCF調用

但是,我不想每次撥打我的服務時都複製粘貼完全相同的try-catch塊。有什麼方法可以使用委託只寫一次try-catch塊?我還想要捕獲異常消息。

我想這樣稱呼它:

// This method returns void 
TryCatchHelper(x => x.WCFMethod1(param1, param2)); 

// This method has a return value but no params 
var returnValue = TryCatchHelper(x => x.WCFMethod2()); 

編輯: 這裏是我的代碼看起來像現在:

User GetUser(int Id) 
{ 
    User returnUser = null; 

    try 
    { 
     // Open WCF channel, etc. 
     returnUser = myWCFClient.GetUser(Id); 
    } 
    catch (TimeoutException exception) 
    { 
     Log(exception.Message); 
     // Abort WCF factory 
    } 
    catch (CommunicationException exception) 
    { 
     Log(exception.Message); 
     // Abort WCF factory 
    } 

    return returnUser; 
} 

我不想用這個相同的try-catch塊我在存儲庫中設置的每一種方法。我試圖做這樣的事情,但它給了我一個參數上的錯誤。我知道我不能正確使用它們,但我需要一種方法來定義一個委託,它可以站在所有WCF方法調用我想讓:

delegate object WCFAction(params object[] parameters); 

object DoWCFAction(WCFAction action, params object[] parameters) 
{ 
    object returnValue = null; 

    try 
    { 
     // Open WCF channel, etc. 
     returnValue = action(parameters); 
    } 
    catch (TimeoutException exception) 
    { 
     Log(exception.Message); 
     // Abort WCF factory 
    } 
    catch (CommunicationException exception) 
    { 
     Log(exception.Message); 
     // Abort WCF factory 
    } 

    return returnValue; 
} 

void MainMethod() 
{ 
    // Compiler error 
    User user = DoWCFAction(GetUser, 1); 
} 
+0

你是否已經嘗試過與代表,並沒有做到這一點?如果是這樣,請向我們展示不工作的代碼。如果沒有,請在對SO提出問題之前進行研究。 – Lokerim 2013-02-16 02:57:26

+0

你想讓你的catch塊做什麼?記錄異常並返回確切的結果(對於具有返回值的方法)?重試? – carlosfigueira 2013-02-16 03:02:16

+0

我想在某處記錄錯誤,以便管理員查看超時和連接問題。爲我嘗試做的事添加了代碼。 – chani 2013-02-18 20:01:49

回答

1

你可以建立一個類這樣。很抱歉,我們這裏有兩個例外處理程序,而不是一個:

class Logger 
{ 
    // handle wcf calls that return void 
    static public void ExecWithLog(Action action) 
    { 
     try 
     { 
      action(); 
     } 
     catch(Exception e) 
     { 
      Log(e); 
      throw; 
     } 
    } 

    // handle wcf calls that return a value 
    static public T ExecWithLog<T>(Func<T> action) 
    { 
     T result = default(T); 
     try 
     { 
      result = action(); 
     } 
     catch (Exception e) 
     { 
      Log(e); 
      throw; 
     } 

     return result; 
    } 

    static void Log(Exception e) 
    { 
     System.Diagnostics.Debug.WriteLine(e.ToString()); 
    } 

} 

然後,打電話給你的方法:

static void Main(string[] args) 
{ 
    Logger.ExecWithLog(() => DoSomethingReturnVoid()); 
    Logger.ExecWithLog(() => DoSomethingReturnVoidParamInt(5)); 
    int a = Logger.ExecWithLog<int>(() => DoSomethingReturnInt()); 
    string b = Logger.ExecWithLog<string>(() => DoSomethingReturnStringParamInt(5)); 
} 
+0

謝謝,使用Func 正是我所期待的。 – chani 2013-02-19 00:24:44