问:是否有更好的方法来处理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); }
}
守着星空守着你
UYOU
慕容3067478
随时随地看视频慕课网APP
相关分类