如何捕获特定的SqlException错误?
是否有更好的方法来处理SqlExceptions?
下面的示例依赖于解释消息中的文本。
如果表不存在,我有一个现有的try catch来处理。
忽略了我可以首先检查表是否存在的事实。
try{
    //code
}
catch(SqlException sqlEx)
{
        if (sqlEx.Message.StartsWith("Invalid object name"))
        {
            //code
        }
        else
            throw;
}
没有try catch显示重复的密钥异常
if (sqlEx.Message.StartsWith("Cannot insert duplicate key row in object"))//-- to see list of error messages: select * from sys.messages where language_id = 1033 order by message_idpublic 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); }
}
回答:
SqlException具有您可以检查的Number属性。对于重复错误,数字为2601。
catch (SqlException e){
   switch (e.Number)
   {
      case 2601:
         // Do something.
         break;
      default:
         throw;
   }
 }
要获取服务器中所有SQL错误的列表,请尝试以下操作:
 SELECT * FROM sysmessages现在可以在C#6.0中简化
catch (SqlException e) when (e.Number == 2601){
   // Do something.
}
以上是 如何捕获特定的SqlException错误? 的全部内容, 来源链接: utcz.com/qa/428903.html








