I have a class like:
class SampleRepositoryClass
{
void MethodA()
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
void MethodB(int a, int b)
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
List<int> MethodC(int userId)
{
try
{
//do something
}
catch(Exception ex)
{
LogError(ex);
throw ex;
}
}
}
In above example, you can see that in each methods (MethodA, MethodB, MethodC) have try...catch blocks to log the errors and then throw to higher level.
Imagine that when my Repository class might have more than hundred methods and in each method I have try...catch block even if there is only single line of code.
Now, my intention is to reduce these repetitive exception logging code and log all the exceptions at class level instead of method level.
Why re-invent the wheel, when there is such a thing as FREE Post Sharp Express.
It's as easy as adding the PostSharp.dll
as a reference to your project.
After doing that, your repository would look like the following:
[Serializable]
class ExceptionWrapper : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs args)
{
LogError(args.Exception);
//throw args.Exception;
}
}
[ExceptionWrapper]
class SampleRepositoryClass
{
public void MethodA()
{
//Do Something
}
void MethodB(int a, int b)
{
//Do Something
}
List<int> MethodC(int userId)
{
//Do Something
}
}
Adding the ExceptionWrapper
attribute on the class, ensures all properties and methods are encapsulated within a try/catch block. The code in catch will be the code you put in the overriden function OnException() in ExceptionWrapper.
You dont need to write code to rethrow as well. The exception can also be automatically re-thrown if correct flow-behaviors are provided. Please check the documentation for that.
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