SQL Server error constants in ADO.NET

  • Thread starter Thread starter Carl Johansen
  • Start date Start date
C

Carl Johansen

I'm calling a SQL Server statement and I know that it might sometimes return
a "violation of unique key constraint" error (SQL Server error 2627). I'd
like to catch this and handle it - something like this:

Try
cmd.ExecuteScalar()
Catch ex As SqlException
Select Case ex.Number
Case 2627 'Unique constraint violation <-- don't want to
hard code this number
<code to handle violation goes here>
<other cases go here>
End Select
End Try

This is fine, except that I don't want to hard code the value 2627. I
thought there might be some kind of enumeration in ADO.NET that would give
nice names to all these standard errors, but I can't find anything like it.
Is there something I can use, or should I write my own, or just forget about
it and hard-code the error number?

Thanks in advance,
Carl Johansen
http://www.carljohansen.co.uk
 
I am not exactly sure if this can be done as it's more or less provider dependent. I can however suggest you to declare constants in a separate class and use them wherever you would want to catch that specific error code, you will have to hard code the error code only once - during it's declaration. But please be aware of the fact that if you declare your constant in an assembly which is different from the assembly that refers to it, you will have to recompile all those assemblies in case you change the value of the constant and yours is not a public assembly, as the actual value of the constant is substituted by the compiler while compiling.

HTH, Metallikanz!
 
Back
Top