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# ?
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 Severity
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 from the list above or, if you really need it, prepare your own custom error message using sp_addmessage.
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();
}
}
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://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities?view=sql-server-2017:
SQL RAISERROR -> C#:
- 0-10 = fyi*
- 11-16 = you can fix it**
- 17-19 = get admin help
- 20-24 = definitely get admin help***
*(don't throw anything) ┬──┬
**(16 = general)
***(fatal error)
来源:https://stackoverflow.com/questions/22126828/catch-sql-raise-error-in-c-sharp