I would like to create an attribute HandleError
that I would put on a class like this:
[HandleError]
public class Foo
{
public void Do(){}
...
public void Don(){}
}
and it will wrap all the methods in try catch, so I believe it should be something like this:
public class HandleErrorAttribute : Attribute
{
public void Execute()
{
try
{
method.Execute();
}
catch(Exception ex)
{
//log
}
}
}
is this possible ?
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Don't try to catch specific exceptions that are due to bugs - you want them to fail, get logged, then get fixed. And no, you definitely don't want to wrap every method call with a try/catch block. "So they can trace where exceptions occur" - that's what the stack trace is for...
When you have methods that do multiple things you are multiplying the complexity, not adding it. In other words, a method that is wrapped in a try catch has two possible outcomes. You have the non-exception outcome and the exception outcome.
You're looking for something like PostSharp, and it's well worth implementing. However, the implementation is far beyond the scope of this question. Take a look at this link, you'll see it's doing just what you want.
So, download PostSharp, get started with it, and if you have more questions about it then we'd be able to help you out. However, their documentation is insanely good and it's cake to implement.
[Serializable]
public class MyExceptionHandling : OnMethodBoundaryAspect
{
public override void OnException(MethodExecutionArgs args)
{
// here you would perform the logging
}
}
Then on your method you would mark it up with the new attribute:
public class Foo
{
[MyExceptionHandling]
public void Do(){}
[MyExceptionHandling]
public void Don(){}
}
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