简化异常处理

本文关键字:异常处理 | 更新日期: 2023-09-27 18:01:24

我正在创建一个填充数据库的asp.net站点。我的目标是为每个数据库操作打印成功/失败消息。目前,我已经尝试捕获语句为每个下降,插入和创建语句。我的问题是:我可以创建一个执行异常处理的单一方法,它被传递一个方法调用,例如:

public void doWork()
{
  if(exceptionHandling(calculateStuff()) != null)
  {
    div.innerHTML += "there was a problem (print error)";
  }
}
public Exception exceptionHandling(methodCall)
{
  try {
   //execute method call
   calculateStuff();
  }
  catch(Exception error)
  {
    return error;
  }
  public void calculateStuff()
  {
    //calcuate stuff here
  }
}

我的目标是通过减少try/catch语句的数量来减少代码中的重复。上面的方法是可以接受的,还是有更好的方法?

简化异常处理

你总是可以这样做(我已经稍微修改了你的代码,它不再返回一个Exception,而是调用代码提供了调用异常的代码;对我来说,这是一个可读性的问题,如果你喜欢你的方法,你可以修改它):

public void SomeOperation(MyObject param)
{
   //do something
}
public void SomeOtherOperation(AnotherObject param)
{
   //do something else
}
public void SafelyExecute<TParam>(Action<TParam> methodToExecute,
                                  Action<Exception> exceptionHandler,
                                  TParam param)
{
    try
    {
        methodToExecute(param);
    }
    catch (Exception e)
    {
        exceptionHandler(e);
    }
}
public void DoWork()
{
   SafelyExecute(SomeOperation,
                 e => div.innerHTML += "there was a problem" + e.Message,
                 myObjectInstance);
   SafelyExecute(SomeOtherOperation,
                 e => div.innerHTML += "there was a different problem" + e.Message,
                 anotherObjectInstance);
}

你绝对可以做到这一点,我的建议是使用Postsharp,你可以从nugget下载,它像一个魅力。例如,看看下面的代码

/// <summary> 
/// Aspect that, when applied on a method, catches all its exceptions, 
/// assign them a GUID, log them, and replace them by an <see cref="InternalException"/>. 
/// </summary> 
[Serializable] 
public class ExceptionPolicyAttribute : OnExceptionAspect 
{ 
    /// <summary> 
    /// Method invoked upon failure of the method to which the current 
    /// aspect is applied. 
    /// </summary> 
    /// <param name="args">Information about the method being executed.</param> 
  public override void OnException(MethodExecutionArgs args) 
    { 
        Guid guid = Guid.NewGuid(); 
        Trace.TraceError("Exception {0} handled by ExceptionPolicyAttribute: {1}", 
            guid, args.Exception.ToString()); 
        throw new InternalException( 
            string.Format("An internal exception has occurred. Use the id {0} " + 
            "for further reference to this issue.", guid)); 
    } 
} 

和使用这个属性只需在我们的方法,如下所示:-

[ExceptionPolicy]
public void doWork()
{
  ///Your code
}

所以当dowork中发生错误时,它将重定向到用于异常处理的代码段。

查看更多信息:-

http://www.postsharp.net/blog/post/Day-6-Your-code-after-PostSharp