I am currently working with an ASP.NET MVC 4 project, using C#.
I would like to create an extension method that accepts various types of methods, wraps those methods in a try/catch, and then returns the results of the method call if the call succeeds.
Here is what I have so far:
public static object HandleServerError(this object obj)
{
object result = null;
try
{
result = obj;
}
catch (Exception ex)
{
ErrorHandlers.ThrowServerErrorException(ex);
}
return result;
}
Here is an example of the extension method in use:
var test = webClient.DownloadString(uri).HandleServerError().ToString();
This works ok, but the webClient.DownloadString(uri) part is executed and then passed into HandleServerError as a string which is NOT what I want.
What I am wanting to do is INJECT webClient.DownloadString(uri) into the extension method so that the actual method call is wrapped into a try/catch.
Please note
I realize that there are arguments against try/catch statements, but not looking to start a debate over the subject–the core of this question is centered on the dependency injection problem. Thanks for all answers though!
You need to create an extension method for a callback (a
Func<T>), not an object.Something like this:
And in use it would look something like this:
But this whole thing would probably be better implemented with a regular method call than extension methods.