在 C# 中捕获 SQL 引发错误 [英] Catch SQL raise error in C#
问题描述
我在 SQL 过程中产生了 raise 错误:
I generate the raise error in SQL procedure:
RAISERROR('已经存在',-10,-10)
但我无法在 C# 中使用以下代码捕获它
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();
}
}
如何在 C# 中捕获引发的错误?
How can I catch the raised error in C# ?
推荐答案
SEVERITY 值小于或等于 10 的 RAISERROR 不会在 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 Severities.
11 到 16 之间的 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)
否则,您可以从上面的列表中选择另一个错误代码,或者,如果您确实需要它,请使用 sp_addmessage.
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.
这篇关于在 C# 中捕获 SQL 引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!