How to use try catch in several methods?

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

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 good way to have only one catch attempt and pass a generic method in that try catch?

Intuitively, I would use a delegate, but should delegates have the same signature?

Thanks in advance.

Sincerely.

+2
source share
2 answers

Whenever you see such code, you can apply the Template method template .

Maybe 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);
}

Etc...

+8
source

This may be helpful for 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);

    }
}
0
source

Source: https://habr.com/ru/post/1677380/


All Articles