Handle Exception in Class Library with Attribute

2019-09-02 19:02发布

问题:

In a class Library, I am trying to handle exception with Attributes in Class Library. Is there a way to do without AOP (PostSharp) ?

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{

    public void OnException(){
    try {

    }
    catch (Exception) {

    }}
}

And I want to decorate attribute like this.

[HandleError]
public void SampleMethod()
{
  throw new Exception();
}

回答1:

Simply put, you can't easily. You could use AOP from another library (for example Spring.NET). The only difference would be that Spring.NET works at runtime, while Postsharp works at compile time.

You could even use Fody to do some code rewriting at compile time, like PostSharp.

Note that if you simply want to do some logging on an exception and you don't need to remove the exception from the stack (you don't want to "eat" it or change it), then you could simply add a FirstChanceException handler. Note that this would slow quite much everything, because you would need to use reflection to check for the presence of the attribute. And if you wanted to walk the stack it would become even slower! (and much more complex)