How can I avoid duplicated try catch blocks

后端 未结 4 1069
我在风中等你
我在风中等你 2021-02-08 06:18

I have several methods that look like this:

public void foo()
{
   try 
   {
      doSomething();
   }
   catch(Exception e)
   {
      Log.Error(e);
   }
 }
         


        
4条回答
  •  长情又很酷
    2021-02-08 07:11

    You can use delegates and lambdas:

    private void ExecuteWithLogging(Action action) {
        try {
            action();
        } catch (Exception e) {
            Log.Error(e);
        }
    }
    
    public void fooSimple() {
        ExecuteWithLogging(doSomething);
    }
    
    public void fooParameter(int myParameter) {
        ExecuteWithLogging(() => doSomethingElse(myParameter));
    }
    
    public void fooComplex(int myParameter) {
        ExecuteWithLogging(() => {
            doSomething();
            doSomethingElse(myParameter);
        });
    }
    

    In fact, you could rename ExecuteWithLogging to something like ExecuteWebserviceMethod and add other commonly used stuff, such as checking credentials, opening and closing a database connection, etc.

提交回复
热议问题