Reputation: 1621
I generate the raise error in SQL procedure:
RAISERROR('Already exist',-10,-10)
but I can not catch it using the following code in C#
catch (SqlException ex)
{
bResult = false;
if (ex.Errors[0].Number == -10)
{
CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);
if ((savePoint != null))
savePoint.Rollback();
}
}
How can I catch the raised error in C# ?
Upvotes: 33
Views: 46739
Reputation: 216353
RAISERRORs with a SEVERITY value under or equal to 10 are not caught on the C# side because I suppose they are considered just warnings as you can see from the list at Database Engine Error Severities.
SEVERITY values between 11 and 16 are errors that can be corrected by the user, so, for example, you can try with:
RAISERROR('Already exist',16,1)
Otherwise, you could choose another error code from the list above or, if you really need it, prepare your own custom error message using sp_addmessage.
Upvotes: 63
Reputation: 1
Use an error code within 11-16, or just use 16 for a "general" case.
RAISERROR('Already exists',16,1)
Why? Here's my summary of https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities?view=sql-server-2017:
SQL RAISERROR -> C#:
*(don't throw anything) ┬──┬
**(16 = general)
***(fatal error)
Upvotes: 0
Reputation: 499372
Your if statement is where things fail. Assuming that the first error in the collection is indeed the one you are looking for (it might not be).
SqlError.Number
is not the value that you set in RAISERROR
.
Use SqlError.Class
to retrieve the severity of the error, or SqlError.State
to check the state (both are -10 in your example. so difficult to tell which out you mean):
catch (SqlException ex)
{
bResult = false;
if (ex.Errors[0].Class == -10)
{
CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);
if ((savePoint != null))
savePoint.Rollback();
}
}
Upvotes: 11