Reputation: 51
I'm trying to handle an exception I know its ErrorCode is 26, but it does not return the right integer, giving me -2146232060.
Screenshot of QuickWatch with the exception description
So instead of writing this:
catch (SqlException e)
{
if (e.ErrorCode == 26)
{
//my code
}
}
I have to use this:
catch (SqlException e)
{
if (e.Message.ToUpper().Contains("ERROR: 26"))
{
//my code
}
}
Why is it returning -2146232060 and how can I get 26 so I don't need to compare all that string values?
Upvotes: 5
Views: 9868
Reputation: 946
I think what you want to be looking at is SqlException.Number (which is SQL's error number) and not SqlException.ErrorCode (which is the SQL driver error number).
static void Main(string[] args) {
try {
var connection = new SqlConnection(@"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Sandbox;Integrated Security=SSPI;");
connection.Open();
var command = new SqlCommand("throw 50000, 'oops', 1;", connection);
command.ExecuteNonQuery();
}
catch (SqlException ex) {
Console.WriteLine(ex.ErrorCode + ": " + ex.Number + ": " + ex.Message);
for (int i = 0; i < ex.Errors.Count; i++)
Console.WriteLine(ex.Errors[i].Number + ": " + ex.Errors[i].Message);
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
};
}
... yields ...
-2146232060: 50000: oops
50000: oops
Much more information about SqlException on MSDN and about the specific error you are receiving here.
Upvotes: 4