Wrap calls of several methods (each of which has different signatures) in one handler

I have several method calls in a third-party library. These methods have a wide variety of different signature / parameter combinations.

There are certain errors that the library of third-party developers generates that I would like to catch and process, and since the resolution is the same, I would like this to take place in one handler.

So, I want to have a way that essentially takes as a parameter a function (delegate) and its arguments and calls it inside some try / catch logic.

I don’t know if this is possible simply impossible, or I don’t get the syntax correctly, but I can’t figure out how to handle the fact that the signature for each method passed is different.

Any suggestions?

+5
source share
1 answer

You can use Actionand Func<T>to wrap methods and closures to pass arguments.

public TResult CallMethod<TResult>(Func<ThirdPartyClass, TResult> func)
{
    try
    {
        return func(this.wrappedObject);
    }
    catch(ThirdPartyException e)
    {
        // Handle
    }
}

public void CallMethod(Action<ThirdPartyClass> method)
{
    this.CallMethod(() => { method(this.WrappedObject); return 0; });
}

Then you can use this via:

var result = wrapper.CallMethod(thirdParty => thirdParty.Foo(bar, baz));

Edit: The assumption above was that you were completing an instance of a third-party library. Given (from your comments) that these are static methods, you can simply use:

public static TResult CallMethod<TResult>(Func<TResult> func)
{
    try
    {
        return func();
    }
    catch(ThirdPartyException e)
    {
        // Handle
    }
}

public static void CallMethod(Action method)
{
    CallMethod(() => { method(); return 0; });
}

And then call through:

var result = Wrapper.CallMethod(() => ThirdParty.Foo(bar, baz));
+7
source

All Articles