29

我在 SQL 过程中生成引发错误:

RAISERROR('Already exist',-10,-10)

但我无法在 C# 中使用以下代码捕获它

catch (SqlException ex)
{
    bResult = false;                   
    if (ex.Errors[0].Number == -10)
    {
        CommonTools.vAddToLog("bInsertNewUser", "ManageUsers", ex.Message);
        if ((savePoint != null))
            savePoint.Rollback();
    }
} 

如何在 C# 中捕获引发的错误?

4

3 回答 3

58

SEVERITY 值小于或等于 10 的 RAISERROR 不会在 C# 端捕获,因为我认为它们只是警告,正如您从数据库引擎错误严重性的列表中看到的那样。

11 到 16 之间的 SEVERITY 值是用户可以纠正的错误,因此,例如,您可以尝试:

RAISERROR('Already exist',16,1)

否则,您可以从上面的列表中选择另一个错误代码,或者,如果您确实需要它,请使用sp_addmessage准备您自己的自定义错误消息。

于 2014-03-02T11:24:14.010 回答
10

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();
    }
} 
于 2014-03-02T11:19:52.610 回答
0

使用 11-16 内的错误代码,或仅使用 16 表示“一般”情况。

RAISERROR('Already exists',16,1)

为什么?这是我对https://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-error-severities?view=sql-server-2017的总结:

SQL RAISERROR -> C#:

  • 0-10 = 仅供参考*
  • 11-16 = 你可以修复它**
  • 17-19 = 获得管理员帮助
  • 20-24 = 肯定得到管理员帮助***

*(不要扔东西)┬──┬</p>

**(16 = 一般)

***(致命错误)

于 2018-12-08T03:41:45.473 回答