How to catch an exception where an interesting detail is in the error code?

My database connection procedure may fail, for example, if the credentials are incorrect. In this case, a general OleDbException is generated with the ErrorCode code -2147217843 . The message gives an error, for example

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

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

    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
+3
source share
1 answer

You can define error codes that interest you as int enum, which can be easily ported to int. I am not too familiar with VB, but I can show you in C # (should be easily converted):

public enum OleDbErrorCodes : int
{
    DB_SEC_E_AUTH_FAILED = -2147217843
}

Catch Enum int :

catch (System.Data.OleDb.OleDbException ex)
{
    if (ex.ErrorCode == (int)OleDbErrorCodes.DB_SEC_E_AUTH_FAILED)
    {
        // Log exception
    }
}
+1

Source: https://habr.com/ru/post/1742111/


All Articles