How can I avoid duplicated try catch blocks

后端 未结 4 1082
我在风中等你
我在风中等你 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条回答
  •  猫巷女王i
    2021-02-08 06:51

    If you don't want to use an AOP approach, a method used at one of my previous employers for common exception handling across a set of class was to have a base class with a method similar to the following

        protected TResult DoWrapped(Func action)
        {
            try
            {
                return action();
            }
            catch (Exception)
            {
                // Do something
                throw;
            }
        }
    

    With methods looking like.

        public object AMethod(object param)
        {
            return DoWrapped(() =>
                          {
                              // Do stuff
                              object result = param;
                              return result;
                          });
        }
    

    Can't remember exactly, it's been a while. But similar to this.

提交回复
热议问题