c# - handle exceptions with attributes -


can please explain, in easy/simple way, how handle exception via attributes?

for example if have simple code this:

class test{ static void main(string[] args){     try {             console.writeline("div= "+ division(0));         }         catch (dividebyzeroexception e)         {             console.writeline("attempted divide 0 -->" + e.message);         }          console.readline();        }      public static int division(int i){  return 10 / i; } } 

how can change code using attributes?

this cannot done .net out of box.

tl;dr - there no "very easy/simple way (...) handle exception via attributes"


you're trying handle exceptions in aop way (aspect oriented programming), attach aspects methods - using attributes, example.

postsharp allows this:

without postsharp:

public class orderfulfillmentservice   {      public void fulfill( order order )       {         try          {            // stuff.           }          catch ( exception e )         {              if ( exceptionhandler.handle(e) )                  throw;         }       }   }  

with postsharp:

public class orderfulfillmentservice   {      [handleexception]       public void fulfill( order order )       {          // stuff.      }  } 

beware of downsides of using aop though: code might become less readable (as isn't written sequentially) , less maintainable.


instead of using attributes, use castle interceptor/dynamicproxy

you need create interceptor wraps around object , intercepts calls it. @ runtime, castle make interceptor either extend concrete class or implement common interface - means you'll able inject interceptor piece of code targets intercepted class. code this:

public class interceptor : iinterceptor {     public void intercept(iinvocation invocation)     {        try{             invocation.proceed();         } catch(exception ex) {            //add "post execution" calls on invocation's target         }     } } 

introduction aop castle: http://docs.castleproject.org/windsor.introduction-to-aop-with-castle.ashx


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -