【问题标题】:How do I catch an Exception where the interesting detail is in the Error Code?如何捕获错误代码中有趣细节的异常?
【发布时间】:2010-04-21 13:45:21
【问题描述】:

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

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

我如何捕捉到这个?使用错误代码 -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

【问题讨论】:

    标签: .net error-handling


    【解决方案1】:

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

    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
        }
    }
    

    【讨论】:

    • 当然,由于错误值是以十六进制定义的,因此您可以将十六进制用于枚举(0x80040E4D 用于 C#,&H80040E4D 用于 VB)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 2019-09-08
    • 2019-12-28
    • 2015-12-18
    • 2011-08-20
    • 2015-06-11
    相关资源
    最近更新 更多