.netexceptionoledbconnectionhresult

How to catch specific OleDbException?


I need to catch the following specific exception:

System.Data.OleDb.OleDbException was caught ErrorCode=-2147467259
Message="The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again." Source="Microsoft JET Database Engine" StackTrace: at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()

I'm not sure what ErrorCode is but it looks unreliable.

Can I rely on Message being identical across platforms?

Can I somehow use the OleDbHResult hr value found in the stack trace? (See https://stackoverflow.com/a/991660/327528)

Is the only solution to do a text search of Message for words like duplicate and primary key?


Solution

  • The JET error code for a OleDbException can be found from:

    OleDbError.SQLState
    

    which is 3022 for the exception provided in the question.