views:

86

answers:

1

My database connection routine can fail, for example, if incorrect credentials are supplied. In this case, a general OleDbException is thrown, with an ErrorCode of -2147217843. The message gives an error such as

No error message available, result code:
DB_SEC_E_AUTH_FAILED(0x80040E4D)

How do I catch this? Using the error code -2147217843 seems a bit "magic numbers".

    Try
        mCon = New OleDbConnection(connectionString)
        mCon.Open()

    Catch ex As OleDbException
        If ex.ErrorCode = -2147217843 Then
            Engine.logger.Fatal("Invalid username and/or password", ex)
            Throw
        End If
    Catch ex As Exception
        Engine.logger.Fatal("Could not connect to the database", ex)
        Throw
    End Try
+1  A: 

You could define the error codes you are interested in as an int Enum which can be easily cast to an Int. I'm not too familiar with VB, but can show you in C# (should be easy to convert):

public enum OleDbErrorCodes : int
{
    DB_SEC_E_AUTH_FAILED = -2147217843
}

Then in your Catch block you could cast the Enum back to an int like so:

catch (System.Data.OleDb.OleDbException ex)
{
    if (ex.ErrorCode == (int)OleDbErrorCodes.DB_SEC_E_AUTH_FAILED)
    {
        // Log exception
    }
}
Dan Diplo
AAT
Yeah, good point.
Dan Diplo