如何捕获特定的SqlException错误?

问:是否有更好的方法来处理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); }

}


守着星空守着你
浏览 1065回答 3
3回答

UYOU

有点像 请参阅数据库引擎错误的原因和解决方案class SqllErrorNumbers{    public const int BadObject = 208;   public const int DupKey = 2627;}try{   ...}catch(SqlException sex){   foreach(SqlErrorCode err in sex.Errors)   {      switch (err.Number)      {      case SqlErrorNumber.BadObject:...      case SqllErrorNumbers.DupKey: ...      }   }}但问题是,我们会TRY/CATCH 在 T-SQL(存储过程)内部建立一个良好的DAL层,并使用类似异常处理和嵌套事务的模式。遗憾的是,T-SQL TRY/CATCH块无法引发原始错误代码,而必须引发新错误,且代码大于50000。这使客户端处理问题。在下一版本的SQL Server中,有一个新的THROW构造,该构造允许重新引发T-SQL catch块中的原始异常。

慕容3067478

最好使用错误代码,而不必解析。try{}catch (SqlException exception){    if (exception.Number == 208)    {    }    else        throw;}如何确定应使用208:select message_idfrom sys.messageswhere text like 'Invalid object name%'
打开App,查看更多内容
随时随地看视频慕课网APP