【问题标题】:Error handling using events, checking if an error happened and react accordingly使用事件处理错误,检查是否发生错误并做出相应反应
【发布时间】:2010-11-26 16:22:42
【问题描述】:

我有一个对象,比如Order,如果发生错误,它会引发ErrorOccurred 事件。如果我正在运行一些代码,例如 .aspx 页面的代码隐藏,其中公共 Order 注册为 WithEvents 并且我想在运行更多代码之前检查是否发生错误,我该怎么做这?我不能简单地检查theOrder.ErrorOccurred。我是否必须创建一个在事件处理程序 (OnErrorOccurred) 中切换的本地布尔标志?或者有更好的方法吗?

谢谢!

例子:

Public WithEvents theOrder As New Order

Public Sub DoStuff() 
    theOrder.DoSomething()
    If theOrder.ErrorOccurred Then
        do stuff
    End If
End Sub

【问题讨论】:

    标签: asp.net vb.net events error-handling


    【解决方案1】:

    使用 Try Catch 块

    Try
    'try your code here
    Catch somevariablenamehere As Exception
    'use methods from Exception class to get to know the error better and how to deal with it
    Finally
    'this is optional, If you want to do something finally, like cleaning up etc. You can do here
    End Try
    'to end the Try block
    

    【讨论】:

      【解决方案2】:

      为什么不使用结构化错误处理?

      Try
         'Code that may raise an error.
      Catch
         'Code to handle the error.
      Finally
         'Code to do any final clean up.
      End Try
      

      http://support.microsoft.com/kb/315965

      这就是它的目的。

      如果有人调用 DoSomething 但他们不知道他们需要检查 theOrder.ErrorOccurred,则可能会出现问题。基于 DoSomething 正在做什么,允许调用方法并让它安静地失败可能是一个问题。

      如果做某事确实在做记录,让它失败。如果它正在完成订单流程..

      布莱恩

      【讨论】:

        【解决方案3】:

        这似乎是一种合理的方法。如果 Order 对象有很多依赖于了解错误的逻辑,那么拥有一个 Status 字段将允许与任何消费者轻松沟通订单的状态,而不是每个人都必须订阅事件并跟踪它自己。

        或者,您可以在 Order 内部跟踪它,如果 Order 处于错误状态,则在访问关键方法时抛出异常。这样做的缺点是需要您进行更多的错误处理,但其优点是可以确保任何 Order 消费者都明确地处理它们。

        【讨论】:

        • 所以为我创建的每个类创建一个 Error 布尔属性有意义吗?
        • 呃...没有。但是,由于您的课程专门引发与错误相关的事件,并且我假设围绕发生的错误也是逻辑密集型的,所以这似乎是合理的。每个班级都不需要这个。
        猜你喜欢
        • 2012-12-18
        • 2018-02-11
        • 1970-01-01
        • 2021-01-20
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多