StrataFrame Forum

Acessing the SQL Error code within a DAL exception

http://forum.strataframe.net/Topic8820.aspx

By Peter Jones - 5/15/2007

Hi,

I want to wrap certain database processing in Try blocks, check any error and retry (within limits) if they are expected, e.g. locking. However, I'm having trouble identifying the native SQL error code within the Exception, e.g.

blTry = True
While blTry
   Try
      Me.FillByStoredProcedure(StoredProc)
      blTry = False
   Catch ex As Exception
      blTry = CheckTheError(ex)
   End Try
End While

I can see the SQL Error Description but I want to evalute errors using native SQL error codes.

Cheers, Peter

By StrataFrame Team - 5/16/2007

Check the type of the exception... you want the SqlException type because it has an Errors collection in it.  You'll probably want to do something like this in your CheckTheError() method:

Public Shared Sub CheckTheError(ByVal ex As Exception)
    '-- Get the reference to the SqlException
    Dim sqlEx As SqlException
    Dim checkingEx As Exception = ex

    '-- Cycle through the InnerExceptions and find the proper exception
    Do
        '-- Attempt to get the exception as an SqlException
        sqlEx = TryCast(checkingEx, SqlException)
        If sqlEx IsNot Nothing Then
            Exit Do '-- You have a reference to the exception
        Else If checkingEx.InnerException IsNot Nothing Then
            checkingEx = checkingEx.InnerException '-- Let it loop to test this new exception
        Else
            '-- The testing exception is not a SqlException and none of the InnerExceptions are either, so
            '  log the top exception and then bail
            Exit Sub
        End If
    Loop

    '-- Handle the sqlEx object with its Errors collection
End Sub

By Peter Jones - 5/16/2007

Hi Ben,

Perfect - thank you.

Cheers, Peter

By StrataFrame Team - 5/17/2007

Glad that worked out for you Smile

Oh, and if the type is a DataLayerSavingException, then it will have the exceptions listed within the SavingErrors collection because there might be more than one, but that's only if you set your business object's ErrorSavingMode to ContinueOnError (non default) and wrap the bo.Save() in a try/catch.