c# - 捕获特定异常

标签 c# exception-handling refactoring

如何使用 C# 捕获特定异常?
在我的数据库中,某些列上有唯一索引。
当用户插入重复记录时抛出此异常:

Cannot insert duplicate key row in object 'dbo.BillIdentity' with unique index 'IX_BillIdentity'. The statement has been terminated.

如何捕捉这个异常?
目前我正在使用这段代码进行检查:

 catch (Exception ex) {
    if (ex.Message.Contains("Cannot insert duplicate key row in object 'dbo._BillIdentity' with unique index 'IX__BillIdentity")) {
        string ScriptKey = "$(function() {ShowMessage('Error');});";
        ScriptManager.RegisterStartupScript(Page, GetType(), "script", ScriptKey, true);
    }
}

我觉得是难闻的代码。
有没有更好的办法?

最佳答案

仅在这种情况下处理 SqlException

[编辑]

检查 MS SQL 服务器中的重复键异常:

try
{
    // try to insert
}
catch (SqlException exception)
{
    if (exception.Number == 2601) // Cannot insert duplicate key row in object error
    {
        // handle duplicate key error
        return;                  
    }
    else
        throw; // throw exception if this exception is unexpected
}

编辑: 2601从哪里来?

select *
from sys.messages
where text like 'Cannot insert duplicate key%'

返回:

message_id  language_id severity is_event_logged text
----------- ----------- -------- --------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2601        1033        14       0               Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.

使用 exception.Number 并引用 sys.messages View ,您可以处理任何特定的 MS SQL 异常。

关于c# - 捕获特定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6120422/

相关文章:

c# - 如何使用DataContext.ExecuteCommand 获取执行后的存储过程返回值?

c# - 为什么动态 IEnumerable 上的 First() 或 ElementAt() 是可等待的?

C# - 将 'object' 参数转换为该对象的类型?

java - 在输入错误值后要求用户再次输入。输入不匹配异常?

c# - 痣和重构代码

javascript - 如何在 apostropecms 中重构客户端 js

C# Linq Query Bad 转换为 RavanDB 中的 RQL

C# 将 ListBox.SelectedItems 复制到另一个变量

java - Optional in orElse-Branch throws Exception

c - 在 C 中捕获浮点溢出