如何捕获SQLServer超时异常

时间:2020-03-05 18:43:41  来源:igfitidea点击:

我需要专门捕获SQL Server超时异常,以便可以对它们进行不同的处理。我知道我可以捕获SqlException,然后检查消息字符串是否包含" Timeout",但想知道是否有更好的方法吗?

try
{
    //some code
}
catch (SqlException ex)
{

    if (ex.Message.Contains("Timeout"))
    {
         //handle timeout
    }
    else
    {
         throw;
    }
}

解决方案

回答

SqlException.ErrorCode属性的值是什么?你可以用吗?

超时时,可能值得检查-2146232060的代码。

我会在数据代码中将其设置为静态const。

回答

要检查超时,我相信我们要检查ex.Number的值。如果为-2,则表示超时。

-2是超时错误代码,它是从DBNETLIB(SQL Server的MDAC驱动程序)返回的。可以通过下载Reflector并在System.Data.SqlClient.TdsEnums下查找TIMEOUT_EXPIRED来看到。

代码将显示为:

if (ex.Number == -2)
{
     //handle timeout
}

演示失败的代码:

try
{
    SqlConnection sql = new SqlConnection(@"Network Library=DBMSSOCN;Data Source=YourServer,1433;Initial Catalog=YourDB;Integrated Security=SSPI;");
    sql.Open();

    SqlCommand cmd = sql.CreateCommand();
    cmd.CommandText = "DECLARE @i int WHILE EXISTS (SELECT 1 from sysobjects) BEGIN SELECT @i = 1 END";
    cmd.ExecuteNonQuery(); // This line will timeout.

    cmd.Dispose();
    sql.Close();
}
catch (SqlException ex)
{
    if (ex.Number == -2) {
        Console.WriteLine ("Timeout occurred");
    }
}