How can I avoid duplicated try catch blocks

后端 未结 4 1076
我在风中等你
我在风中等你 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 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<TResult>(Func<TResult> 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.

    0 讨论(0)
  • 2021-02-08 06:56

    Since you mentioned you're using WCF you can implement IErrorHandler interface and all exceptions would be routed to your method where you can log them.

    • http://www.extremeexperts.com/Net/Articles/ExceptionHandlingInWCF.aspx
    • http://codeifollow.blogspot.com/2010/02/wcf-exception-handling.html
    0 讨论(0)
  • 2021-02-08 07:05

    You may try using: PostSharp

    or try to google 'AOP' - 'Aspect Oriented Programming'. There are more similar techniques on the web.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题