简体   繁体   中英

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

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 ?

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(){}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM