c# - 处理 SQL 自定义异常

标签 c# sql-server-2008 raiserror

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

存储过程会像这样引发错误

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

从上面,如何判断错误是自定义的错误信息。 (ie) 像这样的东西

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

最佳答案

当您引发错误时,您可以提供 MessageId 而不是消息文本。该数字将在异常的 Number 属性中找到:

SQL:

    RAISERROR(50001, 12, 1) 

C#:

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

关于c# - 处理 SQL 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17738963/

相关文章:

sql-server - 选择(无锁定)

sql-server-2008 - 在 SQL 2008 中使用日期查找上周一

c# - RAISERROR―如何与SqlException区分?

c# - 带空格的 Sitecore Lucene 索引搜索词匹配不带空格的同一个词

java - 将java转换为c#代码的工具

sql-server - 通过SQL Server 2008 R2中的不同客户端更新同一记录

Python单元测试失败: should raise value error but not

sql - 使用 RAISERROR 指示 ACCESS DENIED 错误

c# - 如何查看 ASP.Net MVC 中调用的每个 Controller 和操作方法?

c# - 使用 Linq Select 将实体映射到 DTO 的最简洁方法?