Generic logging of function parameters in exception handling

后端 未结 7 1050
渐次进展
渐次进展 2020-12-14 01:15

A lot of my C# code follows this pattern:

void foo(string param1, string param2, string param3)
{
    try
    {
         // do something...
    }
    catch(E         


        
7条回答
  •  囚心锁ツ
    2020-12-14 02:05

    You could use aspect oriented programming with PostSharp (have a look at http://www.postsharp.org, and the tutorial at http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx). Basically you could do something like this:

    public class LogExceptionAttribute : OnExceptionAspect
    {
     public override void OnException(MethodExecutionEventArgs eventArgs)
     {
      log.error("Exception occurred in method {0}", eventArgs); 
     }
    }
    
    [LoggingOnExceptionAspect]
    public foo(int number, string word, Person customer)
    {
       // ... something here throws an exception
    }
    

    Perhaps not quite what you want, but I'm sure it can be adapted to suit your needs.

提交回复
热议问题