【问题标题】:Handling Sql Custom Exception处理 Sql 自定义异常
【发布时间】:2013-07-19 05:52:58
【问题描述】:

如何用c#代码识别sql存储过程引发的自定义错误信息?

存储过程会这样报错

RAISERROR (N'This is message %s %d.', -- Message text.
       10, -- Severity,
       1, -- State,
       N'number', -- First argument.
       5); -- Second argument.

从上面,如何识别错误是自定义错误消息。 (即)像这样的东西

try{
   --actual code here
}
catch(SqlException ex)
{
    --how to check here that the exception is custom one
} 

【问题讨论】:

    标签: c# sql-server-2008 raiserror


    【解决方案1】:

    当您提出错误时,您可以提供 MessageId 而不是 Message 文本。此编号将在 Exception 的 Number 属性中找到:

    SQL:

        RAISERROR(50001, 12, 1) 
    

    C#:

        if (sqlException.Number == 50001)
        {
            throw new CustomSQLException(//whatever);
        }
    

    【讨论】:

    • +1,感谢您的想法。是否可以从 RAISEERROR 本身添加数字和消息?
    • 很遗憾没有。您需要决定提供哪一个。也许您可以使用消息实现一个单独的表并从您的 Exception 类中查询此表?
    • 你的意思是这个的sql表?
    • 是的,但这取决于您要提供的信息的重要性。在正常用例中,我不会这样做,因为您可以提供大量错误编号。
    • 另一个注释:Use sp_addmessage to add user-defined error messages and sp_dropmessage to delete user-defined error messages. 两个注释来自:msdn.microsoft.com/en-us/library/ms178592.aspx
    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2014-02-21
    • 2019-07-15
    • 2021-07-10
    相关资源
    最近更新 更多