Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
CJ7 Avatar asked Jul 29 '26 20:07

CJ7


2 Answers

You're right that the ErrorCode (-2147467259 = 0x80004005 = E_FAIL) is too generic, and relying on the message is very fragile - e.g. consider localization.

I would look at the OleDbException.Errors collection to try to find something more specific.

like image 121
Joe Avatar answered Aug 01 '26 22:08

Joe


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

OleDbError.SQLState

which is 3022 for the exception provided in the question.

like image 29
CJ7 Avatar answered Aug 01 '26 23:08

CJ7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!