捕获SQL Failover异常

本文关键字:异常 Failover SQL 捕获 | 更新日期: 2023-09-27 18:13:09

我正在使用NuGet包Polly来实现捕获故障转移SQL异常的重试逻辑。我在Azure中设置了一个SQL Server始终处于高可用状态。

比起捕获所有SQL异常(这是不正确的),我想捕获发生故障转移时发生的特定SQL异常。

从SSMS,我显示仪表板,然后我能够人为地触发故障转移来测试我的代码。最初,我让所有异常都溢出(所以没有捕获)。然后,我将排队进行故障转移,并查看我的日志,看看引发了什么SQL异常。随后,我能够捕获由于故障转移而发生的所有SQL异常。

我的问题是,这是一个全面的清单吗?在SQL Server故障转移中实现重试逻辑的其他人会捕获任何其他SQL异常吗?

我已经用逻辑尝试了将近100次故障转移,没有任何问题。当然,这并不意味着我已经捕获了全部的故障转移SQL异常。

重试逻辑有Policy.Handle<SqlException>(se => IsFailoverSqlException(se))。当故障转移排队时,根据我在代码中的位置,我看到了下面捕获的三个SQL异常。

    private static bool IsFailoverSqlException(SqlException se)
    {
        return (
                /*
                A network-related or instance-specific error occurred while establishing a connection to SQL Server.
                The server was not found or was not accessible.
                Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
                */
                (se.Class == 20 && se.State == 0 && se.Number == 53) ||
                /*
                Failed while logging Fatal to MT Database: Unable to access availability database 'MedicusMT' because the database replica is not in the PRIMARY or SECONDARY role.
                Connections to an availability database is permitted only when the database replica is in the PRIMARY or SECONDARY role.
                Try the operation again later.
                */
                (se.Class == 14 && se.State == 1 && se.Number == 983) ||
                // A transport-level error has occurred when receiving results from the server.  (provider: Session Provider, error: 19 - Physical connection is not usable)
                (se.Class == 20 && se.State == 0 && se.Number == -1)
            );
    }

捕获SQL Failover异常

使用。NET 4.5及以上版本时,行为发生了变化。SqlException Number可能是Win32 API Number,我发现错误数取决于SQL Server连接中使用的网络库。

为命名管道库设置的值是好的。当与Azure库通信时,有一个临时错误需要处理。不再重复对Azure案例的良好分析。Windows主机上的TCP网络库将有一个Win32内部异常1225。错误号:1225状态:0类:20

我不喜欢的关于SqlException Net45的变化是SqlException。数字是值的混合域。它可以是SQL Server错误或Azure瞬态错误或Win32 API从底层网络库。

如果在工作单元级别应用策略,请考虑为死锁victum SQL Server Error 1205重试

如果您进行实时升级,您可能会发现DBA将杀死PSID错误编号:596,状态:1,类:21

为什么不简化逻辑,只检查连接状态,如果需要创建一个新的连接:conn != null || conn. state != ConnectionState。打开

与本文类似:https://technet.microsoft.com/en-us/library/cc917713.aspx#ECAA