How to use try catch nicely in multiple methods?

北战南征 提交于 2019-12-10 16:58:47

问题


Sorry if my question is stupid, but I have this kind of code :

public Object1 Method1(Object2 parameter)
{
    try
    {
        return this.linkToMyServer.Method1(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

public Object3 Method2(Object4 parameter)
{
    try
    {
        return this.linkToMyServer.Method2(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

/* ... */

public ObjectXX Method50(ObjectXY parameter)
{
    try
    {
        return this.linkToMyServer.Method50(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

I think you see the pattern. Is there a nice way to have only one try catch and to pass a generic method in this try catch ?

Instinctively I'd use a delegate, but delegates have to have the same signature right ?

Thanks in advance.

Regards.


回答1:


Whenever you see code like this you can apply Template Method Pattern.

May be something like this:

private TResult ExecuteWithExceptionHandling<TParam, TResult>(TParam parameter, Func<TParam, TResult> func)
{
    try
    {
        return func(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }
    return default(TResult);
}

public Object1 Method1(Object2 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method1);
}

public Object3 Method2(Object4 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method2);
}

And so on...




回答2:


This might be useful to you.

public object BaseMethod(object[] userParameters,String FunctionName)
{
  try
   {    
          Type thisType = this.GetType();
          MethodInfo theMethod = thisType.GetMethod(FunctionName);
          object returnObj;
          returnObj = theMethod.Invoke(this, userParameters);
          return returnObj;
   }
   catch (Exception e)
   {
            this.Logger(e.InnerException);

    }
}


来源:https://stackoverflow.com/questions/23423043/how-to-use-try-catch-nicely-in-multiple-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!