简化异常处理

时间:2014-05-02 11:17:52

标签: c# asp.net web try-catch

我正在创建一个填充数据库的asp.net站点。我的目标是为每个数据库操作打印成功/失败消息。目前我已经为每个drop,insert和create语句尝试了catch语句。我的问题是:我是否可以创建一个执行异常处理的方法,在该方法中传递一个方法调用,例如:

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语句的数量来减少代码中的重复。以上是可接受的做法还是有更好的方式?

2 个答案:

答案 0 :(得分:1)

您可以随时执行以下操作(我已经稍微修改了您的代码,因为它不再返回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);
}

答案 1 :(得分:1)

你可以明确地做到这一点,我的建议是使用 Postsharp 你可以从金块下载它就像一个魅力..例如看看下面的代码

/// <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)); 
    } 
} 

并在ur方法上使用这个just put属性,如下所示: -

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

因此,只要在dowork中发生错误,它就会重定向到一段代码以进行异常处理。

有关更多信息: -

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