Search code examples
.netvb.netexceptiontry-catchdispose

How to check if exception occured on disposing an event (.Net)


On disposing an object I want to check if an exception is occured to choose wether I do a COMMIT or not. I am working with BAPIs against SAP.

If the creation of a transport order (1) fails, I want to cancel the material document (2). (But this is not of belong to the question)

          Dim rfcFunction As IRfcFunction

    Try

        Using sapConn3 As New SapConnectorV3
          ' (1) Creation of a Transport-Order
        End Using

    Catch ex As Exception

        Using sapConn3 As New SapConnectorV3
          ' (2) Cancel MaterialDocument
          ' (EDIT) The problem can be fixed if I call 
          ' "CommitTransaction" manually at this line. But I want to do 
          ' this automatically on disposing the object
        End Using

        Throw

    End Try

When the Using-Block ends the object gets disposed and at this moment I have to know if a exception occured.

This function is not working, because it states true on both disposings:

 Protected ReadOnly Property ExceptionOccurred() As Boolean
    Get
        Return Runtime.InteropServices.Marshal.GetExceptionCode <> 0
    End Get
End Property

This is how I decide to do a Commit or not (part Dispose():

 Public Sub Dispose() Implements IDisposable.Dispose

     If Not ExceptionOccurred Then

        CommitTransaction()

    End If

Solution

  • You can tackle this from the opposite direction. Instead of trying to notify your SapConnectionV3 object when a failure has occurred, tell it when you've succeeded.

    You simply need to add a Complete() or CompletedSuccessfully() or similar method to your SapConnectorV3, which would set a private bool flag. Call it just before you leave the Using block. Then, inside your Dispose implementation, commit if the flag is true or rollback if it's false.

    Then your calling convention becomes:

    Using sapConn3 As New SapConnectorV3
        ' Do some work.
        sapConn3.Complete()
    End Using ' Now this will commit if Complete was called, or roll back otherwise.