views:

110

answers:

3

I have an object, say Order where if an error occurs, it raises the ErrorOccurred event. If I'm running some code in say, the codebehind for a .aspx page with an public Order registered as WithEvents and I want to check to see if an error has occurred before I run more code, how do I do this? I can't simply check theOrder.ErrorOccurred. Do I have to create a local boolean flag that switches over in the event handler (OnErrorOccurred)? Or is there a better way to do this?

Thanks!

Example:

Public WithEvents theOrder As New Order

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

That seems like a reasonable approach. If there is lots of logic going on with an Order object that depends on knowing about errors, having a Status field would allow easy communication to any consumer what the status of the order was, rather than everyone having to subscribe to the event and track it themselves.

Alternately you could track it internally in the Order and just throw exceptions when critical methods were accessed if the Order was in an error state. This has the disadvantage of making you do more error handling, but would have the advantage of making sure that any Order consumer handled them explicitly.

womp
so it makes sense to create an `Error` boolean property for each class I create?
Jason
Erm... no. But since your class is specifically raising events related to errors and I'm assuming is also logic-intensive surrounding what errors are going on, then it seems reasonable. Every class doesn't need this.
womp
A: 

Why not use structured error handling?

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

This is what it is intended for.

Problems may arize if someone calls DoSomething but thay are unaware that they need to check theOrder.ErrorOccurred. based on what DoSomething is doing, allowing one to call a method and letting it fail quietly can be a problem.

If do something is doing logging sure, let it fail. If it is finalizing an order process..

Brian

brian chandley
A: 

You should use the right tool for the job.

Errors should be caught as Exceptions in a Try/Catch block.

If you are calling Errors what everybody else calls Validation, then you can use a property, method, or even events to communicate the failure to validate correctly.

Alfred Myers