如何捕获错误代码中有趣细节的异常?

时间:2022-10-30 09:09:51

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

我的数据库连接例程可能会失败,例如,如果提供了不正确的凭据。在这种情况下,抛出一般OleDbException,ErrorCode为-2147217843。该消息给出了错误,例如

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".

我怎么抓住这个?使用错误代码-2147217843似乎有点“神奇的数字”。

    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 个解决方案

#1


1  

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):

您可以将您感兴趣的错误代码定义为int Enum,可以轻松地转换为Int。我不太熟悉VB,但可以用C#告诉你(应该很容易转换):

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块中你可以将Enum强制转换为int,如下所示:

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

#1


1  

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):

您可以将您感兴趣的错误代码定义为int Enum,可以轻松地转换为Int。我不太熟悉VB,但可以用C#告诉你(应该很容易转换):

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块中你可以将Enum强制转换为int,如下所示:

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