I'm writing a web service which is wrapper for a vendor's web service, and have a fairly detailed series of catch statements for a call to a vendors web service methods. I have two or three types of exceptions that I'm handling (System.Web.Services.Protocols.SoapException, System.ApplicationException, System.Exception...)
I just realized that most of the errors are the same between their two Create method and their Update method.
Is there any clever way to share the exact same error handlers across multiple methods? I started to write just a common method, but then realized I would have to write at least one common method for each type of exception that I'm handling. It would be great if I could handle all of them the exact same way.
This is a web service with an established interface. Just thinking out loud as I write this, I guess I could put as little code as possible in the web methods, then they could call a shared method? Just want to make sure I'm not missing an obvious trick.
Thanks, Neal
You could create a function that takes a Delegate and then call it with a lambda expression (C# 3) or anonymous method. The function can invoke the passed in Delegate in a try block and handle the exceptions.
private T CallWebService<T>(Func<T> function)
{
try
{
return function();
}
catch (SoapException e)
{
// handle SoapException
}
catch (ApplicationException e)
{
// handle ApplicationException
}
// catch and handle other exceptions
}
public ReturnType CallCreate(ParamType param)
{
return CallWebService(() => WebService.InvokeCreate(param));
}
public ReturnType CallUpdate(ParamType param)
{
return CallWebService(() => WebService.InvokeUpdate(param));
}
If the individual methods need their own specific exceptions handled, then this could be added to the CallCreate and CallUpdate methods.
The above example uses lambda expressions. The equivalent of CallCreate using anonymous methods is:
public ReturnType CallCreate(ParamType param)
{
return CallWebService<ReturnType>(delegate()
{
return WebService.InvokeCreate(param)
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With