diff --git a/docs/quickstart.md b/docs/quickstart.md index 60aca7f..c33baa4 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -70,6 +70,20 @@ The `connectionStringName` setting is required and must be set to the name of th The `schemaName` settings is an optional string value that defaults to `null`. This property is required when database objects are provisioned under a custom schema name. If not specified, a schema name of `dt` is assumed. See the [Multitenancy](multitenancy.md) documentation for more details. +The `transientErrorNumbers` setting is an optional array of SQL error numbers, such as `[47073]`, that should be treated as transient. The provider already retries a built-in set of transient errors (deadlocks, connection drops, Azure SQL throttling, and so on). Errors listed here are retried with the same policy on top of that set. Use it for errors that are transient only in your environment, like Azure SQL error 47073 when DNS resolution briefly falls back to the public endpoint of a database that only allows private endpoint access. The default value is `null`. + +The following errors are treated as transient by default and don't need to be configured: + +| Category | SQL error numbers | +|---|---| +| Azure SQL throttling and resource limits | 10928, 10929, 10936, 40501, 49918, 49919, 49920 | +| Azure SQL service unavailable | 40197, 40613 | +| In-memory OLTP commit and validation conflicts | 41301, 41302, 41305, 41325, 41839 | +| Network and connection errors | 20, 64, 121, 233, 10053, 10054, 10060 | +| Deadlocks | 1205 | + +A `TimeoutException` is also retried. SQL error `-2` (command timeout) is deliberately not retried, because the command may have completed on the server even though the client timed out. + To enable diagnostic logging, you can also add the following `logging` configuration to your **host.json** file: ```json diff --git a/src/DurableTask.SqlServer.AzureFunctions/SqlDurabilityOptions.cs b/src/DurableTask.SqlServer.AzureFunctions/SqlDurabilityOptions.cs index af75b3d..5a0a13c 100644 --- a/src/DurableTask.SqlServer.AzureFunctions/SqlDurabilityOptions.cs +++ b/src/DurableTask.SqlServer.AzureFunctions/SqlDurabilityOptions.cs @@ -31,6 +31,9 @@ class SqlDurabilityOptions [JsonProperty("schemaName")] public string? SchemaName { get; set; } + [JsonProperty("transientErrorNumbers")] + public int[]? TransientErrorNumbers { get; set; } + internal ILoggerFactory LoggerFactory { get; set; } = NullLoggerFactory.Instance; internal SqlOrchestrationServiceSettings GetOrchestrationServiceSettings( @@ -65,6 +68,7 @@ internal SqlOrchestrationServiceSettings GetOrchestrationServiceSettings( LoggerFactory = this.LoggerFactory, WorkItemBatchSize = this.TaskEventBatchSize, WorkItemLockTimeout = this.TaskEventLockTimeout, + TransientErrorNumbers = this.TransientErrorNumbers, }; if (extensionOptions.MaxConcurrentActivityFunctions.HasValue) diff --git a/src/DurableTask.SqlServer/SqlDbManager.cs b/src/DurableTask.SqlServer/SqlDbManager.cs index f3b8a88..1c036b9 100644 --- a/src/DurableTask.SqlServer/SqlDbManager.cs +++ b/src/DurableTask.SqlServer/SqlDbManager.cs @@ -46,7 +46,7 @@ public async Task CreateOrUpgradeSchemaAsync(bool recreateIfExists) try { - using DbDataReader reader = await SqlUtils.ExecuteReaderAsync(command, this.traceHelper); + using DbDataReader reader = await SqlUtils.ExecuteReaderAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); if (await reader.ReadAsync()) { // The first result contains the latest version @@ -114,7 +114,7 @@ public async Task CreateOrUpgradeSchemaAsync(bool recreateIfExists) command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@SemanticVersion", SqlDbType.NVarChar, 100).Value = DTUtils.ExtensionVersion.ToString(); - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); } await dbLock.CommitAsync(); @@ -194,7 +194,7 @@ async Task DoesDatabaseExistAsync(string databaseName, SqlConnection conne command.CommandText = "SELECT 1 FROM sys.databases WHERE name = @databaseName"; command.Parameters.AddWithValue("@databaseName", databaseName); - bool exists = (int?)await SqlUtils.ExecuteScalarAsync(command, this.traceHelper) == 1; + bool exists = (int?)await SqlUtils.ExecuteScalarAsync(command, this.traceHelper, this.settings.TransientErrorNumbers) == 1; return exists; } @@ -205,7 +205,7 @@ async Task CreateDatabaseAsync(string databaseName, SqlConnection connecti try { - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); this.traceHelper.CreatedDatabase(databaseName); return true; } diff --git a/src/DurableTask.SqlServer/SqlOrchestrationService.cs b/src/DurableTask.SqlServer/SqlOrchestrationService.cs index 7ea34bb..d39fede 100644 --- a/src/DurableTask.SqlServer/SqlOrchestrationService.cs +++ b/src/DurableTask.SqlServer/SqlOrchestrationService.cs @@ -205,6 +205,7 @@ public override async Task LockNextEntityWorkItemAsyn reader = await SqlUtils.ExecuteReaderAsync( command, this.traceHelper, + this.settings.TransientErrorNumbers, instanceId: null, cancellationToken); } @@ -311,6 +312,7 @@ public override async Task LockNextEntityWorkItemAsyn await SqlUtils.ExecuteNonQueryAsync( discardCommand, this.traceHelper, + this.settings.TransientErrorNumbers, instanceId, cancellationToken); } @@ -411,7 +413,7 @@ public override async Task RenewTaskOrchestrationWorkItemLockAsync(TaskOrchestra try { - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, workItem.InstanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, workItem.InstanceId); } catch (SqlException e) when (SqlUtils.HasErrorNumber(e, SqlOrchestrationSession.LockLostErrorNumber)) { @@ -501,7 +503,7 @@ public override async Task CompleteTaskOrchestrationWorkItemAsync( try { - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instance.InstanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instance.InstanceId); } catch (SqlException e) when (SqlUtils.IsUniqueKeyViolation(e)) { @@ -581,6 +583,7 @@ public override Task ReleaseTaskOrchestrationWorkItemAsync(TaskOrchestrationWork using DbDataReader reader = await SqlUtils.ExecuteReaderAsync( command, this.traceHelper, + this.settings.TransientErrorNumbers, instanceId: null, shutdownCancellationToken); if (!await reader.ReadAsync(shutdownCancellationToken)) @@ -619,7 +622,7 @@ public override async Task RenewTaskActivityWorkItemLockAs command.Parameters.Add("@LockExpiration", SqlDbType.DateTime2).Value = lockExpiration; string instanceId = workItem.TaskMessage.OrchestrationInstance.InstanceId; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instanceId); workItem.LockedUntilUtc = lockExpiration; return workItem; @@ -636,7 +639,7 @@ public override async Task CompleteTaskActivityWorkItemAsync(TaskActivityWorkIte OrchestrationInstance instance = workItem.TaskMessage.OrchestrationInstance; try { - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instance.InstanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instance.InstanceId); } catch (SqlException e) when (e.Number == 50002) { @@ -679,7 +682,7 @@ public override async Task CreateTaskOrchestrationAsync(TaskMessage creationMess try { - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instance.InstanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instance.InstanceId); } catch (SqlException e) when (e.Number == 50001 /* Instance ID for pending/running instance already exists */) { @@ -696,7 +699,7 @@ public override async Task SendTaskOrchestrationMessageAsync(TaskMessage message command.Parameters.AddOrchestrationEventsParameter("@NewOrchestrationEvents", message, this.settings.SchemaName, this.traceHelper); string instanceId = message.OrchestrationInstance.InstanceId; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instanceId); } public override async Task WaitForOrchestrationAsync( @@ -748,6 +751,7 @@ public override async Task WaitForOrchestrationAsync( using DbDataReader reader = await SqlUtils.ExecuteReaderAsync( command, this.traceHelper, + this.settings.TransientErrorNumbers, instanceId, cancellationToken); @@ -769,7 +773,7 @@ public override async Task GetOrchestrationHistoryAsync(string instanceI command.Parameters.Add("@InstanceID", SqlDbType.VarChar, size: 100).Value = instanceId; command.Parameters.Add("@GetInputsAndOutputs", SqlDbType.Bit).Value = true; // There's no clean way for the caller to specify this currently - using DbDataReader reader = await SqlUtils.ExecuteReaderAsync(command, this.traceHelper, instanceId); + using DbDataReader reader = await SqlUtils.ExecuteReaderAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instanceId); List history = ReadHistoryEvents(reader, executionIdFilter); return DTUtils.SerializeToJson(history); @@ -814,7 +818,7 @@ public override async Task ForceTerminateTaskOrchestrationAsync(string instanceI command.Parameters.Add("@InstanceID", SqlDbType.VarChar, size: 100).Value = instanceId; command.Parameters.Add("@Reason", SqlDbType.VarChar, size: -1 /* max */).Value = reason; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, instanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, instanceId); } public async Task PurgeOrchestrationHistoryAsync(IEnumerable instanceIds) @@ -833,7 +837,7 @@ public async Task PurgeOrchestrationHistoryAsync(IEnumerable instan command.Parameters.AddInstanceIDsParameter("@InstanceIDs", instanceIds, this.settings.SchemaName); Stopwatch latencyStopwatch = Stopwatch.StartNew(); - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); int purgedInstanceCount = (int)instancesDeletedReturnValue.Value; if (purgedInstanceCount > 0) { @@ -856,7 +860,7 @@ public override async Task PurgeOrchestrationHistoryAsync( command.Parameters.Add("@ThresholdTime", SqlDbType.DateTime2).Value = maxThresholdDateTimeUtc; command.Parameters.Add("@FilterType", SqlDbType.TinyInt).Value = (int)timeRangeFilterType; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); } public override async Task PurgeInstanceStateAsync(string instanceId) @@ -987,6 +991,7 @@ public async Task> GetManyOrchestrations using DbDataReader reader = await SqlUtils.ExecuteReaderAsync( command, this.traceHelper, + this.settings.TransientErrorNumbers, instanceId: null, cancellationToken); @@ -1013,7 +1018,7 @@ public async Task RewindTaskOrchestrationAsync(string instanceId, string reason) command.Parameters.Add("@InstanceID", SqlDbType.VarChar, size: 100).Value = instanceId; command.Parameters.Add("@Reason", SqlDbType.VarChar, size: -1 /* max */).Value = reason; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers); } /// diff --git a/src/DurableTask.SqlServer/SqlOrchestrationServiceSettings.cs b/src/DurableTask.SqlServer/SqlOrchestrationServiceSettings.cs index 10916ee..84aa0d6 100644 --- a/src/DurableTask.SqlServer/SqlOrchestrationServiceSettings.cs +++ b/src/DurableTask.SqlServer/SqlOrchestrationServiceSettings.cs @@ -4,6 +4,7 @@ namespace DurableTask.SqlServer { using System; + using System.Collections.Generic; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -198,6 +199,19 @@ public SqlOrchestrationServiceSettings(string connectionString, string? taskHubN [JsonProperty("extendedSessionIdleTimeout")] public TimeSpan ExtendedSessionIdleTimeout { get; set; } = TimeSpan.FromSeconds(30); + /// + /// Gets or sets additional SQL error numbers that should be treated as transient and retried, + /// on top of the built-in list of transient errors. + /// + /// + /// Use this for errors that are not normally transient but occur transiently in a particular environment, + /// for example Azure SQL error 47073 when DNS resolution briefly falls back to the public endpoint of a + /// database that only allows private endpoint access. Commands that fail with one of these errors are + /// retried using the same retry policy as the built-in transient errors. + /// + [JsonProperty("transientErrorNumbers")] + public IReadOnlyCollection? TransientErrorNumbers { get; set; } + /// /// Gets a SQL connection string associated with the configured task hub. /// diff --git a/src/DurableTask.SqlServer/SqlOrchestrationSession.cs b/src/DurableTask.SqlServer/SqlOrchestrationSession.cs index ad6519e..4a3a1cd 100644 --- a/src/DurableTask.SqlServer/SqlOrchestrationSession.cs +++ b/src/DurableTask.SqlServer/SqlOrchestrationSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace DurableTask.SqlServer @@ -108,7 +108,7 @@ public async Task ReleaseLockAsync() command.Parameters.Add("@InstanceID", SqlDbType.VarChar, 100).Value = this.instanceId; command.Parameters.Add("@LockedBy", SqlDbType.VarChar, 100).Value = this.lockedByValue; - await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.instanceId); + await SqlUtils.ExecuteNonQueryAsync(command, this.traceHelper, this.settings.TransientErrorNumbers, this.instanceId); } catch (Exception e) { @@ -135,6 +135,7 @@ async Task> FetchAsync(DateTime newLockExpiration) using DbDataReader reader = await SqlUtils.ExecuteReaderAsync( command, this.traceHelper, + this.settings.TransientErrorNumbers, this.instanceId, this.shutdownToken); diff --git a/src/DurableTask.SqlServer/SqlUtils.cs b/src/DurableTask.SqlServer/SqlUtils.cs index ad06d80..9825fcb 100644 --- a/src/DurableTask.SqlServer/SqlUtils.cs +++ b/src/DurableTask.SqlServer/SqlUtils.cs @@ -908,12 +908,14 @@ static IEnumerable GetInstanceIdRecords(IEnumerable insta public static Task ExecuteReaderAsync( DbCommand command, LogHelper traceHelper, + IReadOnlyCollection? transientErrorNumbers, string? instanceId = null, CancellationToken cancellationToken = default) { return ExecuteSprocAndTraceAsync( command, traceHelper, + transientErrorNumbers, instanceId, cmd => cmd.ExecuteReaderAsync(cancellationToken), cancellationToken); @@ -922,12 +924,14 @@ public static Task ExecuteReaderAsync( public static Task ExecuteNonQueryAsync( DbCommand command, LogHelper traceHelper, + IReadOnlyCollection? transientErrorNumbers, string? instanceId = null, CancellationToken cancellationToken = default) { return ExecuteSprocAndTraceAsync( command, traceHelper, + transientErrorNumbers, instanceId, cmd => cmd.ExecuteNonQueryAsync(cancellationToken), cancellationToken); @@ -936,12 +940,14 @@ public static Task ExecuteNonQueryAsync( public static Task ExecuteScalarAsync( DbCommand command, LogHelper traceHelper, + IReadOnlyCollection? transientErrorNumbers, string? instanceId = null, CancellationToken cancellationToken = default) { return ExecuteSprocAndTraceAsync( command, traceHelper, + transientErrorNumbers, instanceId, cmd => cmd.ExecuteScalarAsync(cancellationToken), cancellationToken); @@ -950,6 +956,7 @@ public static Task ExecuteScalarAsync( static async Task ExecuteSprocAndTraceAsync( DbCommand command, LogHelper traceHelper, + IReadOnlyCollection? transientErrorNumbers, string? instanceId, Func> executor, CancellationToken cancellationToken) @@ -957,7 +964,7 @@ static async Task ExecuteSprocAndTraceAsync( var context = new SprocExecutionContext(); try { - return await WithRetry(command, executor, context, traceHelper, instanceId); + return await WithRetry(command, executor, context, traceHelper, transientErrorNumbers, instanceId); } catch (SqlException e) when (cancellationToken.IsCancellationRequested) { @@ -1024,7 +1031,14 @@ public static DateTime ToSqlUtcDateTime(this DateTime dateTime, DateTime default } } - static async Task WithRetry(DbCommand command, Func> executor, SprocExecutionContext context, LogHelper traceHelper, string? instanceId, int maxRetries = 5) + static async Task WithRetry( + DbCommand command, + Func> executor, + SprocExecutionContext context, + LogHelper traceHelper, + IReadOnlyCollection? transientErrorNumbers, + string? instanceId, + int maxRetries = 5) { context.RetryCount = 0; @@ -1041,7 +1055,7 @@ static async Task WithRetry(DbCommand command, Func> ex } catch (Exception e) { - if (!IsTransient(e)) + if (!IsTransient(e, transientErrorNumbers)) { // Not a retriable exception throw; @@ -1072,7 +1086,7 @@ static async Task WithRetry(DbCommand command, Func> ex } } - static bool IsTransient(Exception exception) + internal static bool IsTransient(Exception exception, IReadOnlyCollection? additionalTransientErrorNumbers = null) { if (exception is SqlException sqlException) { @@ -1176,6 +1190,12 @@ static bool IsTransient(Exception exception) // Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated. //case -2: } + + // User-configured error numbers that should also be treated as transient + if (additionalTransientErrorNumbers != null && additionalTransientErrorNumbers.Contains(error.Number)) + { + return true; + } } return false; diff --git a/test/DurableTask.SqlServer.AzureFunctions.Tests/ExtendedSessionOptionsTests.cs b/test/DurableTask.SqlServer.AzureFunctions.Tests/ExtendedSessionOptionsTests.cs index 5af04ea..1dde9c6 100644 --- a/test/DurableTask.SqlServer.AzureFunctions.Tests/ExtendedSessionOptionsTests.cs +++ b/test/DurableTask.SqlServer.AzureFunctions.Tests/ExtendedSessionOptionsTests.cs @@ -39,7 +39,25 @@ public void UnconfiguredTimeoutMapsFrameworkDefault() Assert.True(frameworkDefault > 0, "Expected a positive framework default for the unconfigured case."); } - static SqlOrchestrationServiceSettings GetSettings(DurableTaskOptions extensionOptions) + [Fact] + public void MapsTransientErrorNumbers() + { + var sqlOptions = new SqlDurabilityOptions { TransientErrorNumbers = new[] { 47073, 4060 } }; + + SqlOrchestrationServiceSettings settings = GetSettings(new DurableTaskOptions(), sqlOptions); + + Assert.Equal(new[] { 47073, 4060 }, settings.TransientErrorNumbers); + } + + [Fact] + public void UnconfiguredTransientErrorNumbersMapToNull() + { + SqlOrchestrationServiceSettings settings = GetSettings(new DurableTaskOptions()); + + Assert.Null(settings.TransientErrorNumbers); + } + + static SqlOrchestrationServiceSettings GetSettings(DurableTaskOptions extensionOptions, SqlDurabilityOptions? sqlOptions = null) { IConfiguration configuration = new ConfigurationBuilder() .AddInMemoryCollection(new[] @@ -53,7 +71,7 @@ static SqlOrchestrationServiceSettings GetSettings(DurableTaskOptions extensionO .Setup(resolver => resolver.Resolve("SQLDB_Connection")) .Returns(configuration.GetSection("SQLDB_Connection")); - return new SqlDurabilityOptions().GetOrchestrationServiceSettings( + return (sqlOptions ?? new SqlDurabilityOptions()).GetOrchestrationServiceSettings( extensionOptions, connectionInfoResolver.Object); } diff --git a/test/DurableTask.SqlServer.Tests/Unit/SqlUtilsTransientTests.cs b/test/DurableTask.SqlServer.Tests/Unit/SqlUtilsTransientTests.cs new file mode 100644 index 0000000..49ff261 --- /dev/null +++ b/test/DurableTask.SqlServer.Tests/Unit/SqlUtilsTransientTests.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace DurableTask.SqlServer.Tests.Unit +{ + using System; + using System.Linq; + using System.Reflection; + using Microsoft.Data.SqlClient; + using Xunit; + + public class SqlUtilsTransientTests + { + // Azure SQL: "Reason: An instance-specific error occurred while establishing a connection to SQL Server. + // Connection was denied since Deny Public Network Access is set to Yes." Not transient by default. + const int DenyPublicNetworkAccess = 47073; + + [Theory] + [InlineData(1205)] // deadlock + [InlineData(40613)] // database not currently available + [InlineData(10054)] // transport-level error + public void BuiltInErrorNumbersAreTransient(int errorNumber) + { + SqlException e = CreateSqlException(errorNumber); + + Assert.True(SqlUtils.IsTransient(e)); + Assert.True(SqlUtils.IsTransient(e, Array.Empty())); + } + + [Fact] + public void UnknownErrorNumberIsNotTransientByDefault() + { + SqlException e = CreateSqlException(DenyPublicNetworkAccess); + + Assert.False(SqlUtils.IsTransient(e)); + Assert.False(SqlUtils.IsTransient(e, additionalTransientErrorNumbers: null)); + Assert.False(SqlUtils.IsTransient(e, new[] { 50000, 12345 })); + } + + [Fact] + public void ConfiguredErrorNumberIsTransient() + { + SqlException e = CreateSqlException(DenyPublicNetworkAccess); + + Assert.True(SqlUtils.IsTransient(e, new[] { DenyPublicNetworkAccess })); + } + + [Fact] + public void ConfiguredErrorNumbersApplyToAnyErrorInTheCollection() + { + SqlException e = CreateSqlException(50000, DenyPublicNetworkAccess); + + Assert.False(SqlUtils.IsTransient(e)); + Assert.True(SqlUtils.IsTransient(e, new[] { DenyPublicNetworkAccess })); + } + + [Fact] + public void NonSqlExceptionsAreUnaffected() + { + int[] extra = new[] { DenyPublicNetworkAccess }; + + Assert.True(SqlUtils.IsTransient(new TimeoutException(), extra)); + Assert.False(SqlUtils.IsTransient(new InvalidOperationException(), extra)); + } + + // SqlError, SqlErrorCollection and SqlException have no public constructors, + // so build them through their internal APIs. + static SqlException CreateSqlException(params int[] errorNumbers) + { + const BindingFlags NonPublicInstance = BindingFlags.NonPublic | BindingFlags.Instance; + + var errors = (SqlErrorCollection)Activator.CreateInstance(typeof(SqlErrorCollection), nonPublic: true)!; + MethodInfo add = typeof(SqlErrorCollection).GetMethod("Add", NonPublicInstance)!; + + ConstructorInfo errorCtor = typeof(SqlError) + .GetConstructors(NonPublicInstance) + .Where(c => c.GetParameters().FirstOrDefault()?.ParameterType == typeof(int)) + .OrderBy(c => c.GetParameters().Length) + .First(); + + foreach (int number in errorNumbers) + { + object?[] args = errorCtor.GetParameters() + .Select((p, i) => i == 0 + ? number + : p.ParameterType == typeof(string) ? $"Simulated SQL error {number}" + : p.ParameterType.IsValueType ? Activator.CreateInstance(p.ParameterType) + : null) + .ToArray(); + add.Invoke(errors, new[] { errorCtor.Invoke(args) }); + } + + MethodInfo create = typeof(SqlException).GetMethod( + "CreateException", + BindingFlags.NonPublic | BindingFlags.Static, + binder: null, + new[] { typeof(SqlErrorCollection), typeof(string) }, + modifiers: null)!; + return (SqlException)create.Invoke(null, new object[] { errors, "16.0" })!; + } + } +}