Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attribute that will wrap all methods in class with try { } catch

Tags:

c#

.net

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 ?

like image 577
Omu Avatar asked Nov 02 '12 12:11

Omu


People also ask

How do you use try catch in class?

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.

Should every method have try catch?

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...

Why should I not wrap every block in try catch?

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.


1 Answers

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(){}
}
like image 177
Mike Perrenoud Avatar answered Nov 07 '22 08:11

Mike Perrenoud