Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap multiple method calls (that each have different signatures) in a single handler

Tags:

c#

I have multiple calls to methods in a 3rd party library. These methods have a wide variety of different signatures / parameter combinations.

There are specific errors that the 3rd party library generates that I would like to catch and handle, and since the resolution is the same I would like it to take place in a single handler.

So I want to be able to have a method that essentially takes in as parameters a function (delegate) and its arguments, and invokes it inside some try/catch logic.

I don't know if its just not possible or I'm not getting the syntax right, but I can't figure out how to handle the fact that the signature for each method being passed in is different.

Any suggestions?

like image 915
bkr Avatar asked Jun 18 '12 17:06

bkr


1 Answers

You could use Action and Func<T> to wrap the 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; });
}

You could then use this via:

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

Edit: The above was assuming you were wrapping an instance of the third party library. Given (from your comments) that these are static methods, you can just 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 via:

var result = Wrapper.CallMethod(() => ThirdParty.Foo(bar, baz));
like image 81
Reed Copsey Avatar answered Oct 03 '22 09:10

Reed Copsey