如何使用 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/