问:有没有更好的方法来处理 SqlExceptions?
以下示例依赖于解释消息中的文本。
Eg1:如果表不存在,我有一个现有的 try catch 来处理。
忽略我可以首先检查表是否存在的事实。
try
{
//code
}
catch(SqlException sqlEx)
{
if (sqlEx.Message.StartsWith("Invalid object name"))
{
//code
}
else
throw;
}
eg2:没有显示重复键异常的try catch
if (sqlEx.Message.StartsWith("Cannot insert duplicate key row in object"))
解决方案:我的SqlExceptionHelper的启动
//-- to see list of error messages: select * from sys.messages where language_id = 1033 order by message_id
public static class SqlExceptionHelper
{
//-- rule: Add error messages in numeric order and prefix the number above the method
//-- 208: Invalid object name '%.*ls'.
public static bool IsInvalidObjectName(SqlException sex)
{ return (sex.Number == 208); }
//-- 2601: Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.
public static bool IsDuplicateKey(SqlException sex)
{ return (sex.Number == 2601); }
}