diff --git a/.editorconfig b/.editorconfig index b9e03bb637f3..fa462349198b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -240,6 +240,9 @@ dotnet_diagnostic.CA2016.severity = warning # CA2200: Rethrow to preserve stack details dotnet_diagnostic.CA2200.severity = warning +# CA2201: Do not raise reserved exception types +dotnet_diagnostic.CA2201.severity = warning + # CA2208: Instantiate argument exceptions correctly dotnet_diagnostic.CA2208.severity = warning @@ -316,7 +319,7 @@ dotnet_diagnostic.IDE0200.severity = warning dotnet_style_allow_multiple_blank_lines_experimental = false dotnet_diagnostic.IDE2000.severity = warning -[{eng/tools/**.cs,**/{test,testassets,samples,Samples,perf,scripts,stress}/**.cs}] +[{eng/tools/**.cs,**/{test,testassets,samples,Samples,perf,benchmarkapps,scripts,stress}/**.cs,src/Hosting/Server.IntegrationTesting/**.cs,src/Servers/IIS/IntegrationTesting.IIS/**.cs,src/Shared/Http2cat/**.cs,src/Testing/**.cs}] # CA1018: Mark attributes with AttributeUsageAttribute dotnet_diagnostic.CA1018.severity = suggestion # CA1507: Use nameof to express symbol names @@ -387,6 +390,8 @@ dotnet_diagnostic.CA2007.severity = suggestion dotnet_diagnostic.CA2008.severity = suggestion # CA2012: Use ValueTask correctly dotnet_diagnostic.CA2012.severity = suggestion +# CA2201: Do not raise reserved exception types +dotnet_diagnostic.CA2201.severity = suggestion # CA2249: Use string.Contains instead of string.IndexOf to improve readability. dotnet_diagnostic.CA2249.severity = suggestion # IDE0005: Remove unnecessary usings diff --git a/src/Components/Components/src/Routing/StringSegmentAccumulator.cs b/src/Components/Components/src/Routing/StringSegmentAccumulator.cs index 1cf483ade98a..99e20e2ace90 100644 --- a/src/Components/Components/src/Routing/StringSegmentAccumulator.cs +++ b/src/Components/Components/src/Routing/StringSegmentAccumulator.cs @@ -16,11 +16,7 @@ public ReadOnlyMemory this[int index] { get { - if (index >= count) - { - throw new IndexOutOfRangeException(); - } - + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, count); return count == 1 ? _single : _multiple![index]; } } diff --git a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs index 6aeccbcc43ec..7edc56420263 100644 --- a/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs +++ b/src/Components/WebAssembly/JSInterop/src/WebAssemblyJSRuntime.cs @@ -100,7 +100,7 @@ private IJSStreamReference DeserializeJSStreamReference(string serializedStreamR var jsStreamReference = JsonSerializer.Deserialize(serializedStreamReference, JsonSerializerOptions); if (jsStreamReference is null) { - throw new NullReferenceException($"Unable to parse the {nameof(serializedStreamReference)}."); + throw new ArgumentException($"Failed to parse as {nameof(IJSStreamReference)}.", nameof(serializedStreamReference)); } return jsStreamReference; diff --git a/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs b/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs index edc12177136a..717a4e20efff 100644 --- a/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs +++ b/src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs @@ -291,7 +291,7 @@ public KeyValuePair this[int index] { if (index < 0 || index >= Count) { - throw new IndexOutOfRangeException(nameof(index)); + throw new ArgumentOutOfRangeException(nameof(index)); } return _values[index]; diff --git a/src/Hosting/Hosting/src/Internal/ConfigureBuilder.cs b/src/Hosting/Hosting/src/Internal/ConfigureBuilder.cs index 4d887c71eee9..80d23945cd47 100644 --- a/src/Hosting/Hosting/src/Internal/ConfigureBuilder.cs +++ b/src/Hosting/Hosting/src/Internal/ConfigureBuilder.cs @@ -43,7 +43,7 @@ private void Invoke(object? instance, IApplicationBuilder builder) } catch (Exception ex) { - throw new Exception(string.Format( + throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, "Could not resolve a service of type '{0}' for the parameter '{1}' of method '{2}' on type '{3}'.", parameterInfo.ParameterType.FullName, diff --git a/src/Hosting/Hosting/src/Internal/HostingRequestFinishedLog.cs b/src/Hosting/Hosting/src/Internal/HostingRequestFinishedLog.cs index 65feb02a5d5c..38ca653148c5 100644 --- a/src/Hosting/Hosting/src/Internal/HostingRequestFinishedLog.cs +++ b/src/Hosting/Hosting/src/Internal/HostingRequestFinishedLog.cs @@ -44,7 +44,7 @@ internal sealed class HostingRequestFinishedLog : IReadOnlyList new KeyValuePair(nameof(request.Path), request.Path.Value), 10 => new KeyValuePair(nameof(request.QueryString), request.QueryString.Value), 11 => new KeyValuePair("{OriginalFormat}", OriginalFormat), - _ => throw new IndexOutOfRangeException(nameof(index)), + _ => throw new ArgumentOutOfRangeException(nameof(index)), }; } } diff --git a/src/Hosting/Hosting/src/Internal/HostingRequestStartingLog.cs b/src/Hosting/Hosting/src/Internal/HostingRequestStartingLog.cs index 68af45f74144..f7e9e2f13f21 100644 --- a/src/Hosting/Hosting/src/Internal/HostingRequestStartingLog.cs +++ b/src/Hosting/Hosting/src/Internal/HostingRequestStartingLog.cs @@ -32,7 +32,7 @@ internal sealed class HostingRequestStartingLog : IReadOnlyList new KeyValuePair(nameof(_request.Path), _request.Path.Value), 8 => new KeyValuePair(nameof(_request.QueryString), _request.QueryString.Value), 9 => new KeyValuePair("{OriginalFormat}", OriginalFormat), - _ => throw new IndexOutOfRangeException(nameof(index)), + _ => throw new ArgumentOutOfRangeException(nameof(index)), }; public HostingRequestStartingLog(HttpContext httpContext) diff --git a/src/Hosting/Hosting/test/ConfigureBuilderTests.cs b/src/Hosting/Hosting/test/ConfigureBuilderTests.cs index d73698536eda..df48c178ea1d 100644 --- a/src/Hosting/Hosting/test/ConfigureBuilderTests.cs +++ b/src/Hosting/Hosting/test/ConfigureBuilderTests.cs @@ -23,7 +23,7 @@ public void CapturesServiceExceptionDetails() var builder = new ConfigureBuilder(methodInfo); Action action = builder.Build(instance: null); - var ex = Assert.Throws(() => action.Invoke(applicationBuilder)); + var ex = Assert.Throws(() => action.Invoke(applicationBuilder)); Assert.NotNull(ex); Assert.Equal($"Could not resolve a service of type '{typeof(CrasherService).FullName}' for the parameter" diff --git a/src/Hosting/TestHost/src/RequestLifetimeFeature.cs b/src/Hosting/TestHost/src/RequestLifetimeFeature.cs index c615bd8c3cff..32fafff504fa 100644 --- a/src/Hosting/TestHost/src/RequestLifetimeFeature.cs +++ b/src/Hosting/TestHost/src/RequestLifetimeFeature.cs @@ -25,7 +25,7 @@ internal void Cancel() void IHttpRequestLifetimeFeature.Abort() { - _abort(new Exception("The application aborted the request.")); + _abort(new OperationCanceledException("The application aborted the request.")); _cancellationTokenSource.Cancel(); } } diff --git a/src/Hosting/TestHost/test/HttpContextBuilderTests.cs b/src/Hosting/TestHost/test/HttpContextBuilderTests.cs index 641026928317..c984bfa07a33 100644 --- a/src/Hosting/TestHost/test/HttpContextBuilderTests.cs +++ b/src/Hosting/TestHost/test/HttpContextBuilderTests.cs @@ -338,7 +338,7 @@ public async Task CallingAbortInsideHandlerShouldSetRequestAborted() }); var server = new TestServer(builder); - var ex = await Assert.ThrowsAsync(() => server.SendAsync(c => { })); + var ex = await Assert.ThrowsAsync(() => server.SendAsync(c => { })); Assert.Equal("The application aborted the request.", ex.Message); await requestAborted.Task.DefaultTimeout(); } diff --git a/src/Hosting/TestHost/test/RequestLifetimeTests.cs b/src/Hosting/TestHost/test/RequestLifetimeTests.cs index 988c7da68d75..6067980e101f 100644 --- a/src/Hosting/TestHost/test/RequestLifetimeTests.cs +++ b/src/Hosting/TestHost/test/RequestLifetimeTests.cs @@ -25,7 +25,7 @@ public async Task LifetimeFeature_Abort_TriggersRequestAbortedToken() }); var client = host.GetTestServer().CreateClient(); - var ex = await Assert.ThrowsAsync(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead)); + var ex = await Assert.ThrowsAsync(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead)); Assert.Equal("The application aborted the request.", ex.Message); await requestAborted.Task.DefaultTimeout(); } @@ -41,7 +41,7 @@ public async Task LifetimeFeature_AbortBeforeHeadersSent_ClientThrows() }); var client = host.GetTestServer().CreateClient(); - var ex = await Assert.ThrowsAsync(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead)); + var ex = await Assert.ThrowsAsync(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead)); Assert.Equal("The application aborted the request.", ex.Message); abortReceived.SetResult(); } diff --git a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs index 7477d2ba7fdc..1cddc0f09517 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs @@ -118,7 +118,7 @@ public static AuthenticateResult Fail(Exception failure, AuthenticationPropertie /// The failure message. /// The result. public static AuthenticateResult Fail(string failureMessage) - => Fail(new Exception(failureMessage)); + => Fail(new AuthenticationFailureException(failureMessage)); /// /// Indicates that there was a failure during authentication. @@ -127,5 +127,5 @@ public static AuthenticateResult Fail(string failureMessage) /// Additional state values for the authentication session. /// The result. public static AuthenticateResult Fail(string failureMessage, AuthenticationProperties? properties) - => Fail(new Exception(failureMessage), properties); + => Fail(new AuthenticationFailureException(failureMessage), properties); } diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationFailureException.cs b/src/Http/Authentication.Abstractions/src/AuthenticationFailureException.cs new file mode 100644 index 000000000000..7523009454f6 --- /dev/null +++ b/src/Http/Authentication.Abstractions/src/AuthenticationFailureException.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Authentication; + +/// +/// A generic authentication failure. +/// +public class AuthenticationFailureException : Exception +{ + /// + /// Creates a new instance of + /// with the specified exception . + /// + /// The message that describes the error. + public AuthenticationFailureException(string? message) + : base(message) + { + } + + /// + /// Creates a new instance of + /// with the specified exception and + /// a reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// The exception that is the cause of the current exception, or . + public AuthenticationFailureException(string? message, Exception? innerException) + : base(message, innerException) + { + } +} diff --git a/src/Http/Authentication.Abstractions/src/PublicAPI.Unshipped.txt b/src/Http/Authentication.Abstractions/src/PublicAPI.Unshipped.txt index 7dc5c58110bf..80662da04d55 100644 --- a/src/Http/Authentication.Abstractions/src/PublicAPI.Unshipped.txt +++ b/src/Http/Authentication.Abstractions/src/PublicAPI.Unshipped.txt @@ -1 +1,4 @@ #nullable enable +Microsoft.AspNetCore.Authentication.AuthenticationFailureException +Microsoft.AspNetCore.Authentication.AuthenticationFailureException.AuthenticationFailureException(string? message) -> void +Microsoft.AspNetCore.Authentication.AuthenticationFailureException.AuthenticationFailureException(string? message, System.Exception? innerException) -> void diff --git a/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.cs b/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.cs index b269cd9893eb..3e517f304aba 100644 --- a/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.cs +++ b/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.cs @@ -22,7 +22,7 @@ public object? this[int index] get => index switch { 0 => Arg0, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -85,7 +85,7 @@ public override T GetArgument(int index) return index switch { 0 => (T)(object)Arg0!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -130,7 +130,7 @@ public object? this[int index] { 0 => Arg0, 1 => Arg1, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -198,7 +198,7 @@ public override T GetArgument(int index) { 0 => (T)(object)Arg0!, 1 => (T)(object)Arg1!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -245,7 +245,7 @@ public object? this[int index] 0 => Arg0, 1 => Arg1, 2 => Arg2, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -318,7 +318,7 @@ public override T GetArgument(int index) 0 => (T)(object)Arg0!, 1 => (T)(object)Arg1!, 2 => (T)(object)Arg2!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -367,7 +367,7 @@ public object? this[int index] 1 => Arg1, 2 => Arg2, 3 => Arg3, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -445,7 +445,7 @@ public override T GetArgument(int index) 1 => (T)(object)Arg1!, 2 => (T)(object)Arg2!, 3 => (T)(object)Arg3!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -496,7 +496,7 @@ public object? this[int index] 2 => Arg2, 3 => Arg3, 4 => Arg4, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -579,7 +579,7 @@ public override T GetArgument(int index) 2 => (T)(object)Arg2!, 3 => (T)(object)Arg3!, 4 => (T)(object)Arg4!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -632,7 +632,7 @@ public object? this[int index] 3 => Arg3, 4 => Arg4, 5 => Arg5, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -720,7 +720,7 @@ public override T GetArgument(int index) 3 => (T)(object)Arg3!, 4 => (T)(object)Arg4!, 5 => (T)(object)Arg5!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -775,7 +775,7 @@ public object? this[int index] 4 => Arg4, 5 => Arg5, 6 => Arg6, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -868,7 +868,7 @@ public override T GetArgument(int index) 4 => (T)(object)Arg4!, 5 => (T)(object)Arg5!, 6 => (T)(object)Arg6!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -925,7 +925,7 @@ public object? this[int index] 5 => Arg5, 6 => Arg6, 7 => Arg7, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -1023,7 +1023,7 @@ public override T GetArgument(int index) 5 => (T)(object)Arg5!, 6 => (T)(object)Arg6!, 7 => (T)(object)Arg7!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1082,7 +1082,7 @@ public object? this[int index] 6 => Arg6, 7 => Arg7, 8 => Arg8, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -1185,7 +1185,7 @@ public override T GetArgument(int index) 6 => (T)(object)Arg6!, 7 => (T)(object)Arg7!, 8 => (T)(object)Arg8!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1246,7 +1246,7 @@ public object? this[int index] 7 => Arg7, 8 => Arg8, 9 => Arg9, - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -1354,7 +1354,7 @@ public override T GetArgument(int index) 7 => (T)(object)Arg7!, 8 => (T)(object)Arg8!, 9 => (T)(object)Arg9!, - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.tt b/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.tt index 098d6397318f..42b2b9d9fdcd 100644 --- a/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.tt +++ b/src/Http/Http.Abstractions/src/EndpointFilterInvocationContextOfT.Generated.tt @@ -32,7 +32,7 @@ internal sealed class EndpointFilterInvocationContext<<# foreach (var argumentCo { <# foreach (var argumentCount in Enumerable.Range(0, arity)) { #> <#=argumentCount#> => Arg<#=argumentCount#>, <# } #> - _ => new IndexOutOfRangeException() + _ => new ArgumentOutOfRangeException(nameof(index)) }; set { @@ -98,7 +98,7 @@ internal sealed class EndpointFilterInvocationContext<<# foreach (var argumentCo { <# foreach (var argumentCount in Enumerable.Range(0, arity)) { #> <#=argumentCount#> => (T)(object)Arg<#=argumentCount#>!, <# } #> - _ => throw new IndexOutOfRangeException() + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/Emitters/EndpointParameterEmitter.cs b/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/Emitters/EndpointParameterEmitter.cs index 34c728356ad3..ca188428fa9c 100644 --- a/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/Emitters/EndpointParameterEmitter.cs +++ b/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/Emitters/EndpointParameterEmitter.cs @@ -243,7 +243,7 @@ internal static void EmitBindAsyncPreparation(this EndpointParameter endpointPar codeWriter.WriteLine($"var {endpointParameter.EmitTempArgument()} = await {unwrappedTypeString}.BindAsync(httpContext);"); break; default: - throw new Exception("Unreachable!"); + throw new NotImplementedException($"Unreachable! Unexpected {nameof(BindabilityMethod)}: {endpointParameter.BindMethod}"); } // TODO: Generate more compact code if the type is a reference type and/or the BindAsync return nullability matches the handler parameter type. @@ -291,7 +291,7 @@ internal static void EmitServiceParameterPreparation(this EndpointParameter endp public static string EmitArgument(this EndpointParameter endpointParameter) => endpointParameter.Source switch { EndpointParameterSource.JsonBody or EndpointParameterSource.Route or EndpointParameterSource.RouteOrQuery or EndpointParameterSource.JsonBodyOrService or EndpointParameterSource.FormBody => endpointParameter.IsOptional ? endpointParameter.EmitHandlerArgument() : $"{endpointParameter.EmitHandlerArgument()}!", - EndpointParameterSource.Unknown => throw new Exception("Unreachable!"), + EndpointParameterSource.Unknown => throw new NotImplementedException($"Unreachable! Unexpected {nameof(EndpointParameterSource)}: {endpointParameter.Source}"), _ => endpointParameter.EmitHandlerArgument() }; } diff --git a/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/EndpointParameter.cs b/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/EndpointParameter.cs index 59724330ca9e..593a9f7876bb 100644 --- a/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/EndpointParameter.cs +++ b/src/Http/Http.Extensions/gen/StaticRouteHandlerModel/EndpointParameter.cs @@ -231,7 +231,7 @@ private bool TryGetParsability(IParameterSymbol parameter, WellKnownTypes wellKn ParsabilityMethod.Enum => (string inputArgument, string outputArgument) => $$"""Enum.TryParse<{{parameterType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}}>({{inputArgument}}!, out var {{outputArgument}})""", ParsabilityMethod.Uri => (string inputArgument, string outputArgument) => $$"""Uri.TryCreate({{inputArgument}}!, UriKind.RelativeOrAbsolute, out var {{outputArgument}})""", ParsabilityMethod.String => null, // string parameters don't require parsing - _ => throw new Exception("Unreachable!"), + _ => throw new NotImplementedException($"Unreachable! Unexpected {nameof(ParsabilityMethod)}: {parsabilityMethod}"), }; // Special case handling for specific types diff --git a/src/Http/Routing/src/PathTokenizer.cs b/src/Http/Routing/src/PathTokenizer.cs index 4f378185318d..face95b38e24 100644 --- a/src/Http/Routing/src/PathTokenizer.cs +++ b/src/Http/Routing/src/PathTokenizer.cs @@ -68,10 +68,7 @@ public StringSegment this[int index] { get { - if (index >= Count) - { - throw new IndexOutOfRangeException(); - } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); var currentSegmentIndex = 0; var currentSegmentStart = 1; diff --git a/src/Http/Routing/src/Template/RouteTemplate.cs b/src/Http/Routing/src/Template/RouteTemplate.cs index 9302642f9e24..7a896e770491 100644 --- a/src/Http/Routing/src/Template/RouteTemplate.cs +++ b/src/Http/Routing/src/Template/RouteTemplate.cs @@ -101,11 +101,7 @@ public RouteTemplate(string template, List segments) /// A instance. public TemplateSegment? GetSegment(int index) { - if (index < 0) - { - throw new IndexOutOfRangeException(); - } - + ArgumentOutOfRangeException.ThrowIfNegative(index); return index >= Segments.Count ? null : Segments[index]; } diff --git a/src/Middleware/Rewrite/src/BackReferenceCollection.cs b/src/Middleware/Rewrite/src/BackReferenceCollection.cs index 8a406db5b3d7..dd823d0b3e90 100644 --- a/src/Middleware/Rewrite/src/BackReferenceCollection.cs +++ b/src/Middleware/Rewrite/src/BackReferenceCollection.cs @@ -35,7 +35,7 @@ public string this[int index] } else { - throw new IndexOutOfRangeException($"Cannot access back reference at index {index}. Only {_backReferences.Count} back references were captured."); + throw new ArgumentOutOfRangeException(null, $"Cannot access back reference at index {index}. Only {_backReferences.Count} back references were captured."); } } } diff --git a/src/Middleware/Rewrite/src/IISUrlRewrite/ConditionCollection.cs b/src/Middleware/Rewrite/src/IISUrlRewrite/ConditionCollection.cs index ab88d36bd022..3d26aeb0744b 100644 --- a/src/Middleware/Rewrite/src/IISUrlRewrite/ConditionCollection.cs +++ b/src/Middleware/Rewrite/src/IISUrlRewrite/ConditionCollection.cs @@ -33,7 +33,7 @@ public Condition this[int index] { return _conditions[index]; } - throw new IndexOutOfRangeException($"Cannot access condition at index {index}. Only {_conditions.Count} conditions were captured."); + throw new ArgumentOutOfRangeException(null, $"Cannot access condition at index {index}. Only {_conditions.Count} conditions were captured."); } } diff --git a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs index 39c34ed1943a..9de45043ff7e 100644 --- a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs +++ b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs @@ -545,7 +545,7 @@ public async Task VerifyTrackAllCapturesRuleAndConditionCapture() } [Fact] - public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() + public async Task ThrowArgumentOutOfRangeExceptionWithCorrectMessage() { // Arrange, Act, Assert var options = new RewriteOptions().AddIISUrlRewrite(new StringReader(@" @@ -576,7 +576,7 @@ public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() var server = host.GetTestServer(); - var ex = await Assert.ThrowsAsync(() => server.CreateClient().GetAsync("article/23?p1=123&p2=abc")); + var ex = await Assert.ThrowsAsync(() => server.CreateClient().GetAsync("article/23?p1=123&p2=abc")); Assert.Equal("Cannot access back reference at index 9. Only 5 back references were captured.", ex.Message); } diff --git a/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs b/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs index 0109a6fbbe0d..b433f41a82c7 100644 --- a/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs +++ b/src/Mvc/Mvc.Core/src/Diagnostics/MvcDiagnostics.cs @@ -55,7 +55,7 @@ public BeforeActionEventData(ActionDescriptor actionDescriptor, HttpContext http 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HttpContext), HttpContext), 2 => new KeyValuePair(nameof(RouteData), RouteData), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -106,7 +106,7 @@ public AfterActionEventData(ActionDescriptor actionDescriptor, HttpContext httpC 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HttpContext), HttpContext), 2 => new KeyValuePair(nameof(RouteData), RouteData), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -157,7 +157,7 @@ public BeforeAuthorizationFilterOnAuthorizationEventData(ActionDescriptor action 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(AuthorizationContext), AuthorizationContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -208,7 +208,7 @@ public AfterAuthorizationFilterOnAuthorizationEventData(ActionDescriptor actionD 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(AuthorizationContext), AuthorizationContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -259,7 +259,7 @@ public BeforeResourceFilterOnResourceExecutionEventData(ActionDescriptor actionD 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutingContext), ResourceExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -310,7 +310,7 @@ public AfterResourceFilterOnResourceExecutionEventData(ActionDescriptor actionDe 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutedContext), ResourceExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -361,7 +361,7 @@ public BeforeResourceFilterOnResourceExecutingEventData(ActionDescriptor actionD 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutingContext), ResourceExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -412,7 +412,7 @@ public AfterResourceFilterOnResourceExecutingEventData(ActionDescriptor actionDe 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutingContext), ResourceExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -463,7 +463,7 @@ public BeforeResourceFilterOnResourceExecutedEventData(ActionDescriptor actionDe 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutedContext), ResourceExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -514,7 +514,7 @@ public AfterResourceFilterOnResourceExecutedEventData(ActionDescriptor actionDes 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResourceExecutedContext), ResourceExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -565,7 +565,7 @@ public BeforeExceptionFilterOnException(ActionDescriptor actionDescriptor, Excep 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ExceptionContext), ExceptionContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -616,7 +616,7 @@ public AfterExceptionFilterOnExceptionEventData(ActionDescriptor actionDescripto 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ExceptionContext), ExceptionContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -667,7 +667,7 @@ public BeforeActionFilterOnActionExecutionEventData(ActionDescriptor actionDescr 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutingContext), ActionExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -718,7 +718,7 @@ public AfterActionFilterOnActionExecutionEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutedContext), ActionExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -769,7 +769,7 @@ public BeforeActionFilterOnActionExecutingEventData(ActionDescriptor actionDescr 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutingContext), ActionExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -820,7 +820,7 @@ public AfterActionFilterOnActionExecutingEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutingContext), ActionExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -871,7 +871,7 @@ public BeforeActionFilterOnActionExecutedEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutedContext), ActionExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -922,7 +922,7 @@ public AfterActionFilterOnActionExecutedEventData(ActionDescriptor actionDescrip 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ActionExecutedContext), ActionExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -973,7 +973,7 @@ public BeforeControllerActionMethodEventData(ActionContext actionContext, IReadO 0 => new KeyValuePair(nameof(ActionContext), ActionContext), 1 => new KeyValuePair(nameof(ActionArguments), ActionArguments), 2 => new KeyValuePair(nameof(Controller), Controller), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1032,7 +1032,7 @@ public AfterControllerActionMethodEventData(ActionContext actionContext, IReadOn 1 => new KeyValuePair(nameof(Controller), Controller), 2 => new KeyValuePair(nameof(Controller), Controller), 3 => new KeyValuePair(nameof(Result), Result), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1083,7 +1083,7 @@ public BeforeResultFilterOnResultExecutionEventData(ActionDescriptor actionDescr 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutingContext), ResultExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1134,7 +1134,7 @@ public AfterResultFilterOnResultExecutionEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutedContext), ResultExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1185,7 +1185,7 @@ public BeforeResultFilterOnResultExecutingEventData(ActionDescriptor actionDescr 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutingContext), ResultExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1236,7 +1236,7 @@ public AfterResultFilterOnResultExecutingEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutingContext), ResultExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1287,7 +1287,7 @@ public BeforeResultFilterOnResultExecutedEventData(ActionDescriptor actionDescri 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutedContext), ResultExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1338,7 +1338,7 @@ public AfterResultFilterOnResultExecutedEventData(ActionDescriptor actionDescrip 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ResultExecutedContext), ResultExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1381,7 +1381,7 @@ public BeforeActionResultEventData(ActionContext actionContext, IActionResult re { 0 => new KeyValuePair(nameof(ActionContext), ActionContext), 1 => new KeyValuePair(nameof(Result), Result), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -1424,6 +1424,6 @@ public AfterActionResultEventData(ActionContext actionContext, IActionResult res { 0 => new KeyValuePair(nameof(ActionContext), ActionContext), 1 => new KeyValuePair(nameof(Result), Result), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Mvc/Mvc.Core/src/Infrastructure/ActionMethodExecutor.cs b/src/Mvc/Mvc.Core/src/Infrastructure/ActionMethodExecutor.cs index 57c63674fa39..bedecd52f0c3 100644 --- a/src/Mvc/Mvc.Core/src/Infrastructure/ActionMethodExecutor.cs +++ b/src/Mvc/Mvc.Core/src/Infrastructure/ActionMethodExecutor.cs @@ -50,8 +50,7 @@ public static ActionMethodExecutor GetExecutor(ObjectMethodExecutor executor) } } - Debug.Fail("Should not get here"); - throw new Exception(); + throw new UnreachableException(); } public static ActionMethodExecutor GetFilterExecutor(ControllerActionDescriptor actionDescriptor) => diff --git a/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs b/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs index e8052e8b8dc1..3596394264cb 100644 --- a/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs +++ b/src/Mvc/Mvc.Core/src/MvcCoreLoggerExtensions.cs @@ -300,7 +300,7 @@ public KeyValuePair this[int index] { return new KeyValuePair("ActionName", _action.DisplayName ?? string.Empty); } - throw new IndexOutOfRangeException(nameof(index)); + throw new ArgumentOutOfRangeException(nameof(index)); } } diff --git a/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs b/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs index d8282901fcb4..1f4517d88fd7 100644 --- a/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs +++ b/src/Mvc/Mvc.Razor/src/Diagnostics/MvcDiagnostics.cs @@ -65,7 +65,7 @@ public BeforeViewPageEventData(IRazorPage page, ViewContext viewContext, ActionD 1 => new KeyValuePair(nameof(ViewContext), ViewContext), 2 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 3 => new KeyValuePair(nameof(HttpContext), HttpContext), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -126,6 +126,6 @@ public AfterViewPageEventData(IRazorPage page, ViewContext viewContext, ActionDe 1 => new KeyValuePair(nameof(ViewContext), ViewContext), 2 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 3 => new KeyValuePair(nameof(HttpContext), HttpContext), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Mvc/Mvc.RazorPages/src/Diagnostics/MvcDiagnostics.cs b/src/Mvc/Mvc.RazorPages/src/Diagnostics/MvcDiagnostics.cs index d45a17018abd..ae602a4d4445 100644 --- a/src/Mvc/Mvc.RazorPages/src/Diagnostics/MvcDiagnostics.cs +++ b/src/Mvc/Mvc.RazorPages/src/Diagnostics/MvcDiagnostics.cs @@ -62,7 +62,7 @@ public BeforeHandlerMethodEventData(ActionContext actionContext, IReadOnlyDictio 1 => new KeyValuePair(nameof(Arguments), Arguments), 2 => new KeyValuePair(nameof(HandlerMethodDescriptor), HandlerMethodDescriptor), 3 => new KeyValuePair(nameof(Instance), Instance), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -129,7 +129,7 @@ public AfterHandlerMethodEventData(ActionContext actionContext, IReadOnlyDiction 2 => new KeyValuePair(nameof(HandlerMethodDescriptor), HandlerMethodDescriptor), 3 => new KeyValuePair(nameof(Instance), Instance), 4 => new KeyValuePair(nameof(Result), Result!), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -180,7 +180,7 @@ public BeforePageFilterOnPageHandlerExecutionEventData(CompiledPageActionDescrip 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutionContext), HandlerExecutionContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -231,7 +231,7 @@ public AfterPageFilterOnPageHandlerExecutionEventData(CompiledPageActionDescript 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -282,7 +282,7 @@ public BeforePageFilterOnPageHandlerExecutingEventData(CompiledPageActionDescrip 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutingContext), HandlerExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -333,7 +333,7 @@ public AfterPageFilterOnPageHandlerExecutingEventData(CompiledPageActionDescript 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutingContext), HandlerExecutingContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -384,7 +384,7 @@ public BeforePageFilterOnPageHandlerExecutedEventData(CompiledPageActionDescript 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -435,7 +435,7 @@ public AfterPageFilterOnPageHandlerExecutedEventData(CompiledPageActionDescripto 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerExecutedContext), HandlerExecutedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -486,7 +486,7 @@ public BeforePageFilterOnPageHandlerSelectionEventData(CompiledPageActionDescrip 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -537,7 +537,7 @@ public AfterPageFilterOnPageHandlerSelectionEventData(CompiledPageActionDescript 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -588,7 +588,7 @@ public BeforePageFilterOnPageHandlerSelectedEventData(CompiledPageActionDescript 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -639,6 +639,6 @@ public AfterPageFilterOnPageHandlerSelectedEventData(CompiledPageActionDescripto 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(HandlerSelectedContext), HandlerSelectedContext), 2 => new KeyValuePair(nameof(Filter), Filter), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs index fbd2d2a43f53..0049efeb4b73 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/AttributeDictionary.cs @@ -225,7 +225,7 @@ public void CopyTo(KeyValuePair[] array, int arrayIndex) if (arrayIndex < 0 || arrayIndex >= array.Length) { - throw new IndexOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } for (var i = 0; i < Count; i++) @@ -404,7 +404,7 @@ public void CopyTo(string[] array, int arrayIndex) if (arrayIndex < 0 || arrayIndex >= array.Length) { - throw new IndexOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } for (var i = 0; i < _attributes.Count; i++) @@ -509,7 +509,7 @@ public void CopyTo(string?[] array, int arrayIndex) if (arrayIndex < 0 || arrayIndex >= array.Length) { - throw new IndexOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); } for (var i = 0; i < _attributes.Count; i++) diff --git a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs index 754821b45958..86f0069c555c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Buffers/ViewBuffer.cs @@ -75,7 +75,7 @@ public ViewBufferPage this[int index] { return _currentPage; } - throw new IndexOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(index)); } } diff --git a/src/Mvc/Mvc.ViewFeatures/src/Diagnostics/MvcDiagnostics.cs b/src/Mvc/Mvc.ViewFeatures/src/Diagnostics/MvcDiagnostics.cs index 58d43ba2399b..8b2c5234945c 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/Diagnostics/MvcDiagnostics.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/Diagnostics/MvcDiagnostics.cs @@ -55,7 +55,7 @@ public BeforeViewComponentEventData(ActionDescriptor actionDescriptor, ViewCompo 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ViewComponentContext), ViewComponentContext), 2 => new KeyValuePair(nameof(ViewComponent), ViewComponent), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -114,7 +114,7 @@ public AfterViewComponentEventData(ActionDescriptor actionDescriptor, ViewCompon 1 => new KeyValuePair(nameof(ViewComponentContext), ViewComponentContext), 2 => new KeyValuePair(nameof(ViewComponent), ViewComponent), 3 => new KeyValuePair(nameof(ViewComponentResult), ViewComponentResult), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -164,7 +164,7 @@ public ViewComponentBeforeViewExecuteEventData(ActionDescriptor actionDescriptor 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ViewComponentContext), ViewComponentContext), 2 => new KeyValuePair(nameof(View), View), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -215,7 +215,7 @@ public ViewComponentAfterViewExecuteEventData(ActionDescriptor actionDescriptor, 0 => new KeyValuePair(nameof(ActionDescriptor), ActionDescriptor), 1 => new KeyValuePair(nameof(ViewComponentContext), ViewComponentContext), 2 => new KeyValuePair(nameof(View), View), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -258,7 +258,7 @@ public BeforeViewEventData(IView view, ViewContext viewContext) { 0 => new KeyValuePair(nameof(View), View), 1 => new KeyValuePair(nameof(ViewContext), ViewContext), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -301,7 +301,7 @@ public AfterViewEventData(IView view, ViewContext viewContext) { 0 => new KeyValuePair(nameof(View), View), 1 => new KeyValuePair(nameof(ViewContext), ViewContext), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -368,7 +368,7 @@ public ViewFoundEventData(ActionContext actionContext, bool isMainPage, ActionRe 2 => new KeyValuePair(nameof(Result), Result), 3 => new KeyValuePair(nameof(ViewName), ViewName), 4 => new KeyValuePair(nameof(View), View), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } @@ -435,6 +435,6 @@ public ViewNotFoundEventData(ActionContext actionContext, bool isMainPage, Actio 2 => new KeyValuePair(nameof(Result), Result), 3 => new KeyValuePair(nameof(ViewName), ViewName), 4 => new KeyValuePair(nameof(SearchedLocations), SearchedLocations), - _ => throw new IndexOutOfRangeException(nameof(index)) + _ => throw new ArgumentOutOfRangeException(nameof(index)) }; } diff --git a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs index 001f42c3f752..e5bd967b331e 100644 --- a/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs +++ b/src/Mvc/Mvc.ViewFeatures/src/ViewComponents/DefaultViewComponentInvoker.cs @@ -302,7 +302,7 @@ public KeyValuePair this[int index] { return new KeyValuePair("ViewComponentId", _descriptor.Id); } - throw new IndexOutOfRangeException(nameof(index)); + throw new ArgumentOutOfRangeException(nameof(index)); } } diff --git a/src/Mvc/Mvc.ViewFeatures/test/ViewComponents/ViewViewComponentResultTest.cs b/src/Mvc/Mvc.ViewFeatures/test/ViewComponents/ViewViewComponentResultTest.cs index 1d4104c72b2e..cbdb82df2a96 100644 --- a/src/Mvc/Mvc.ViewFeatures/test/ViewComponents/ViewViewComponentResultTest.cs +++ b/src/Mvc/Mvc.ViewFeatures/test/ViewComponents/ViewViewComponentResultTest.cs @@ -258,7 +258,7 @@ public void Execute_ThrowsIfPartialViewCannotBeFound_MessageUsesAllLocations() public void Execute_DoesNotWrapThrownExceptionsInAggregateExceptions() { // Arrange - var expected = new IndexOutOfRangeException(); + var expected = new ArgumentOutOfRangeException(); var view = new Mock(); view.Setup(v => v.RenderAsync(It.IsAny())) diff --git a/src/Security/Authentication/Core/src/HandleRequestResult.cs b/src/Security/Authentication/Core/src/HandleRequestResult.cs index b4c73e45c713..c337694d6207 100644 --- a/src/Security/Authentication/Core/src/HandleRequestResult.cs +++ b/src/Security/Authentication/Core/src/HandleRequestResult.cs @@ -62,7 +62,7 @@ public class HandleRequestResult : AuthenticateResult /// The failure message. /// The result. public static new HandleRequestResult Fail(string failureMessage) - => Fail(new Exception(failureMessage)); + => Fail(new AuthenticationFailureException(failureMessage)); /// /// Indicates that there was a failure during authentication. @@ -71,7 +71,7 @@ public class HandleRequestResult : AuthenticateResult /// Additional state values for the authentication session. /// The result. public static new HandleRequestResult Fail(string failureMessage, AuthenticationProperties? properties) - => Fail(new Exception(failureMessage), properties); + => Fail(new AuthenticationFailureException(failureMessage), properties); /// /// Discontinue all processing for this request and return to the client. diff --git a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs index e7ee941e0c74..2b7b94a93636 100644 --- a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs @@ -121,13 +121,13 @@ public virtual async Task HandleRequestAsync() } else if (errorContext.Result.Failure != null) { - throw new Exception("An error was returned from the RemoteFailure event.", errorContext.Result.Failure); + throw new AuthenticationFailureException("An error was returned from the RemoteFailure event.", errorContext.Result.Failure); } } if (errorContext.Failure != null) { - throw new Exception("An error was encountered while handling the remote login.", errorContext.Failure); + throw new AuthenticationFailureException("An error was encountered while handling the remote login.", errorContext.Failure); } } diff --git a/src/Security/Authentication/Negotiate/src/Internal/NegotiateState.cs b/src/Security/Authentication/Negotiate/src/Internal/NegotiateState.cs index 4d3e74e160a0..2b0340fc16a7 100644 --- a/src/Security/Authentication/Negotiate/src/Internal/NegotiateState.cs +++ b/src/Security/Authentication/Negotiate/src/Internal/NegotiateState.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Net.Security; -using System.Security.Authentication; using System.Security.Claims; using System.Security.Principal; @@ -30,7 +29,7 @@ public NegotiateState() } else { - error = new AuthenticationException(authStatus.ToString()); + error = new AuthenticationFailureException(authStatus.ToString()); if (IsCredentialError(authStatus)) { status = BlobErrorType.CredentialError; diff --git a/src/Security/Authentication/Negotiate/src/NegotiateHandler.cs b/src/Security/Authentication/Negotiate/src/NegotiateHandler.cs index 12c7395f6663..2fa2442e920b 100644 --- a/src/Security/Authentication/Negotiate/src/NegotiateHandler.cs +++ b/src/Security/Authentication/Negotiate/src/NegotiateHandler.cs @@ -272,7 +272,7 @@ public async Task HandleRequestAsync() } else if (errorContext.Result.Failure != null) { - throw new Exception("An error was returned from the AuthenticationFailed event.", errorContext.Result.Failure); + throw new AuthenticationFailureException("An error was returned from the AuthenticationFailed event.", errorContext.Result.Failure); } } diff --git a/src/Security/Authentication/OAuth/src/OAuthHandler.cs b/src/Security/Authentication/OAuth/src/OAuthHandler.cs index 31f3079634ed..1bb66be053ba 100644 --- a/src/Security/Authentication/OAuth/src/OAuthHandler.cs +++ b/src/Security/Authentication/OAuth/src/OAuthHandler.cs @@ -87,7 +87,7 @@ protected override async Task HandleRemoteAuthenticateAsync { return result; } - var deniedEx = new Exception("Access was denied by the resource owner or by the remote server."); + var deniedEx = new AuthenticationFailureException("Access was denied by the resource owner or by the remote server."); deniedEx.Data["error"] = error.ToString(); deniedEx.Data["error_description"] = errorDescription.ToString(); deniedEx.Data["error_uri"] = errorUri.ToString(); @@ -106,7 +106,7 @@ protected override async Task HandleRemoteAuthenticateAsync failureMessage.Append(";Uri=").Append(errorUri); } - var ex = new Exception(failureMessage.ToString()); + var ex = new AuthenticationFailureException(failureMessage.ToString()); ex.Data["error"] = error.ToString(); ex.Data["error_description"] = errorDescription.ToString(); ex.Data["error_uri"] = errorUri.ToString(); @@ -227,7 +227,7 @@ private static OAuthTokenResponse PrepareFailedOAuthTokenReponse(HttpResponseMes if (exception is null) { var errorMessage = $"OAuth token endpoint failure: Status: {response.StatusCode};Headers: {response.Headers};Body: {body};"; - return OAuthTokenResponse.Failed(new Exception(errorMessage)); + return OAuthTokenResponse.Failed(new AuthenticationFailureException(errorMessage)); } return OAuthTokenResponse.Failed(exception); diff --git a/src/Security/Authentication/OAuth/src/OAuthTokenResponse.cs b/src/Security/Authentication/OAuth/src/OAuthTokenResponse.cs index 2607ce7347c7..e892fdcc80a4 100644 --- a/src/Security/Authentication/OAuth/src/OAuthTokenResponse.cs +++ b/src/Security/Authentication/OAuth/src/OAuthTokenResponse.cs @@ -115,7 +115,7 @@ public void Dispose() result.Append(errorUri); } - var exception = new Exception(result.ToString()); + var exception = new AuthenticationFailureException(result.ToString()); exception.Data["error"] = error.ToString(); exception.Data["error_description"] = errorDescription.ToString(); exception.Data["error_uri"] = errorUri.ToString(); diff --git a/src/Security/Authentication/Twitter/src/TwitterHandler.cs b/src/Security/Authentication/Twitter/src/TwitterHandler.cs index 00147aa4cc41..32377e0063f4 100644 --- a/src/Security/Authentication/Twitter/src/TwitterHandler.cs +++ b/src/Security/Authentication/Twitter/src/TwitterHandler.cs @@ -268,7 +268,7 @@ private async Task ObtainRequestTokenAsync(string callBackUri, Aut var responseParameters = new FormCollection(new FormReader(responseText).ReadForm()); if (!string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.Ordinal)) { - throw new Exception("Twitter oauth_callback_confirmed is not true."); + throw new AuthenticationFailureException("Twitter oauth_callback_confirmed is not true."); } return new RequestToken diff --git a/src/Security/Authentication/test/OAuthTests.cs b/src/Security/Authentication/test/OAuthTests.cs index ef4c447dec33..128e3fa0285b 100644 --- a/src/Security/Authentication/test/OAuthTests.cs +++ b/src/Security/Authentication/test/OAuthTests.cs @@ -437,7 +437,7 @@ public async Task ExchangeCodeAsync_ChecksForErrorInformation(HttpStatusCode htt })); using var server = host.GetTestServer(); - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( () => server.SendAsync("https://www.example.com/oauth-callback?code=random_code&state=protected_state", ".AspNetCore.Correlation.correlationId=N")); } @@ -478,7 +478,7 @@ public async Task ExchangeCodeAsync_FallbackToBasicErrorReporting_WhenErrorInfor })); using var server = host.GetTestServer(); - var exception = await Assert.ThrowsAsync( + var exception = await Assert.ThrowsAsync( () => server.SendAsync("https://www.example.com/oauth-callback?code=random_code&state=protected_state", ".AspNetCore.Correlation.correlationId=N")); } diff --git a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectEventTests.cs b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectEventTests.cs index 8a90d1bf4811..3da118f7e03e 100644 --- a/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectEventTests.cs +++ b/src/Security/Authentication/test/OpenIdConnect/OpenIdConnectEventTests.cs @@ -6,6 +6,7 @@ using System.Net.Http; using System.Security.Claims; using System.Text; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; @@ -62,7 +63,7 @@ public async Task OnMessageReceived_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", ""); }); @@ -131,7 +132,7 @@ public async Task OnTokenValidated_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "id_token=my_id_token&state=protected_state"); }); @@ -240,7 +241,7 @@ public async Task OnAuthorizationCodeReceived_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "id_token=my_id_token&state=protected_state&code=my_code"); }); @@ -346,7 +347,7 @@ public async Task OnTokenResponseReceived_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "id_token=my_id_token&state=protected_state&code=my_code"); }); @@ -454,7 +455,7 @@ public async Task OnTokenValidatedBackchannel_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "state=protected_state&code=my_code"); }); @@ -564,7 +565,7 @@ public async Task OnUserInformationReceived_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "id_token=my_id_token&state=protected_state&code=my_code"); }); @@ -688,7 +689,7 @@ public async Task OnAuthenticationFailed_Fail_NoMoreEventsRun() }; var server = CreateServer(events, AppWritePath); - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return PostAsync(server, "signin-oidc", "id_token=my_id_token&state=protected_state&code=my_code"); }); diff --git a/src/Security/Authentication/test/WsFederation/WsFederationTest.cs b/src/Security/Authentication/test/WsFederation/WsFederationTest.cs index bdbc4ad06a9d..e11ea3c57c73 100644 --- a/src/Security/Authentication/test/WsFederation/WsFederationTest.cs +++ b/src/Security/Authentication/test/WsFederation/WsFederationTest.cs @@ -5,6 +5,7 @@ using System.Net.Http; using System.Security.Claims; using System.Text; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -142,7 +143,7 @@ public async Task ValidUnsolicitedTokenIsRefused() { var httpClient = await CreateClient(); var form = CreateSignInContent("WsFederation/ValidToken.xml", suppressWctx: true); - var exception = await Assert.ThrowsAsync(() => httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form)); + var exception = await Assert.ThrowsAsync(() => httpClient.PostAsync(httpClient.BaseAddress + "signin-wsfed", form)); Assert.Contains("Unsolicited logins are not allowed.", exception.InnerException.Message); } diff --git a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3PendingStream.cs b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3PendingStream.cs index adc7d5bb56dd..af813249434e 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http3/Http3PendingStream.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http3/Http3PendingStream.cs @@ -51,7 +51,7 @@ public async ValueTask ReadNextStreamHeaderAsync(Http3StreamContext contex if (result.IsCanceled) { - throw new Exception(); + throw new OperationCanceledException("The read operation was canceled."); } var readableBuffer = result.Buffer; diff --git a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/PipeWriterHelpers/ConcurrentPipeWriter.cs b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/PipeWriterHelpers/ConcurrentPipeWriter.cs index 0256e7830a23..2f0d3f8ba534 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Infrastructure/PipeWriterHelpers/ConcurrentPipeWriter.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Infrastructure/PipeWriterHelpers/ConcurrentPipeWriter.cs @@ -19,7 +19,7 @@ internal sealed class ConcurrentPipeWriter : PipeWriter private const int MaxSegmentPoolSize = 256; // 1MB private const int MinimumBufferSize = 4096; // 4K - private static readonly Exception _successfullyCompletedSentinel = new Exception(); + private static readonly Exception _successfullyCompletedSentinel = new UnreachableException(); private readonly object _sync; private readonly PipeWriter _innerPipeWriter; diff --git a/src/Shared/HttpSys/NativeInterop/SafeLocalFreeChannelBinding.cs b/src/Shared/HttpSys/NativeInterop/SafeLocalFreeChannelBinding.cs index 4ba23548dd87..5a85bba6a2d3 100644 --- a/src/Shared/HttpSys/NativeInterop/SafeLocalFreeChannelBinding.cs +++ b/src/Shared/HttpSys/NativeInterop/SafeLocalFreeChannelBinding.cs @@ -24,7 +24,9 @@ public static SafeLocalFreeChannelBinding LocalAlloc(int cb) if (result.IsInvalid) { result.SetHandleAsInvalid(); +#pragma warning disable CA2201 // Do not raise reserved exception types throw new OutOfMemoryException(); +#pragma warning restore CA2201 } result.size = cb; diff --git a/src/Shared/Process/ProcessEx.cs b/src/Shared/Process/ProcessEx.cs index bdff075a62cb..44e91b23ca3b 100644 --- a/src/Shared/Process/ProcessEx.cs +++ b/src/Shared/Process/ProcessEx.cs @@ -11,6 +11,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Internal; +using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Internal; @@ -190,7 +191,7 @@ internal string GetFormattedOutput() { if (!_process.HasExited) { - throw new InvalidOperationException($"Process {_process.ProcessName} with pid: {_process.Id} has not finished running."); + Assert.Fail($"Process {_process.ProcessName} with pid: {_process.Id} has not finished running."); } return $"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}"; @@ -215,7 +216,7 @@ public void WaitForExit(bool assertSuccess, TimeSpan? timeSpan = null) } else if (assertSuccess && _process.ExitCode != 0) { - throw new Exception($"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}"); + Assert.Fail($"Process exited with code {_process.ExitCode}\nStdErr: {Error}\nStdOut: {Output}"); } } diff --git a/src/Shared/SignalR/VerifyNoErrorScope.cs b/src/Shared/SignalR/VerifyNoErrorScope.cs index b53536290621..b6c59c846dcf 100644 --- a/src/Shared/SignalR/VerifyNoErrorScope.cs +++ b/src/Shared/SignalR/VerifyNoErrorScope.cs @@ -5,6 +5,7 @@ using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; +using Xunit; namespace Microsoft.AspNetCore.SignalR.Tests; @@ -60,7 +61,7 @@ public void Dispose() return lineMessage; })); - throw new Exception(errorMessage); + Assert.Fail(errorMessage); } } } diff --git a/src/Shared/runtime/Http2/Hpack/DynamicTable.cs b/src/Shared/runtime/Http2/Hpack/DynamicTable.cs index d57242b0521d..821ca75e1478 100644 --- a/src/Shared/runtime/Http2/Hpack/DynamicTable.cs +++ b/src/Shared/runtime/Http2/Hpack/DynamicTable.cs @@ -30,7 +30,10 @@ public ref readonly HeaderField this[int index] { if (index >= _count) { +#pragma warning disable CA2201 // Do not raise reserved exception types + // Helpful to act like static table (array) throw new IndexOutOfRangeException(); +#pragma warning restore CA2201 } index = _insertIndex - index - 1; diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs index ae5f5e67ba4b..797ecee716c8 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs @@ -1706,7 +1706,7 @@ private static void SafeAssert(bool condition, string message, [CallerMemberName { if (!condition) { - throw new Exception($"Assertion failed in {memberName}, at {fileName}:{lineNumber}: {message}"); + throw new InvalidOperationException($"Assertion failed in {memberName}, at {fileName}:{lineNumber}: {message}"); } } diff --git a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Negotiate.cs b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Negotiate.cs index 3d1bbc5ed3e6..810633c73587 100644 --- a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Negotiate.cs +++ b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Negotiate.cs @@ -593,7 +593,7 @@ await WithConnectionAsync( CreateConnection(testHttpHandler, loggerFactory: noErrorScope.LoggerFactory), async (connection) => { - var exception = await Assert.ThrowsAsync(() => connection.StartAsync().DefaultTimeout()); + var exception = await Assert.ThrowsAsync(() => connection.StartAsync().DefaultTimeout()); Assert.Equal("Test error.", exception.Message); }); } diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs index 0b44f234883b..1d56c314f784 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs @@ -476,7 +476,7 @@ private async Task NegotiateAsync(Uri url, HttpClient httpC var negotiateResponse = NegotiateProtocol.ParseResponse(responseBuffer); if (!string.IsNullOrEmpty(negotiateResponse.Error)) { - throw new Exception(negotiateResponse.Error); + throw new InvalidOperationException(negotiateResponse.Error); } Log.ConnectionEstablished(_logger, negotiateResponse.ConnectionId!); return negotiateResponse; diff --git a/src/SignalR/clients/ts/FunctionalTests/ts/HubConnectionTests.ts b/src/SignalR/clients/ts/FunctionalTests/ts/HubConnectionTests.ts index 88d2fdd0d48c..7135ca18f550 100644 --- a/src/SignalR/clients/ts/FunctionalTests/ts/HubConnectionTests.ts +++ b/src/SignalR/clients/ts/FunctionalTests/ts/HubConnectionTests.ts @@ -515,7 +515,7 @@ describe("hubConnection", () => { await resultPromise; expect(false).toBe(true); } catch (err) { - expect((err as any).message).toEqual("An unexpected error occurred invoking 'StreamingConcat' on the server. Exception: Something bad"); + expect((err as any).message).toEqual("An unexpected error occurred invoking 'StreamingConcat' on the server. HubException: Something bad"); } finally { await hubConnection.stop(); } diff --git a/src/SignalR/common/Shared/ClientResultsManager.cs b/src/SignalR/common/Shared/ClientResultsManager.cs index 7bbc0b930824..18fb5a950538 100644 --- a/src/SignalR/common/Shared/ClientResultsManager.cs +++ b/src/SignalR/common/Shared/ClientResultsManager.cs @@ -27,7 +27,7 @@ public Task AddInvocation(string connectionId, string invocationId, Cancel } else { - tcs.SetException(new Exception(completionMessage.Error)); + tcs.SetException(new HubException(completionMessage.Error)); } } )); diff --git a/src/SignalR/server/Core/src/StreamTracker.cs b/src/SignalR/server/Core/src/StreamTracker.cs index f0f9d0513ce1..b317243c7df9 100644 --- a/src/SignalR/server/Core/src/StreamTracker.cs +++ b/src/SignalR/server/Core/src/StreamTracker.cs @@ -70,7 +70,7 @@ public bool TryComplete(CompletionMessage message) { return false; } - converter.TryComplete(message.HasResult || message.Error == null ? null : new Exception(message.Error)); + converter.TryComplete(message.HasResult || message.Error == null ? null : new HubException(message.Error)); return true; } diff --git a/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.ClientResult.cs b/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.ClientResult.cs index da5078458fa2..3b2c396b948e 100644 --- a/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.ClientResult.cs +++ b/src/SignalR/server/SignalR/test/HubConnectionHandlerTests.ClientResult.cs @@ -63,7 +63,7 @@ public async Task CanReturnClientResultErrorToHub() await client.SendHubMessageAsync(CompletionMessage.WithError(invocationMessage.InvocationId, "Client error")).DefaultTimeout(); var completion = Assert.IsType(await client.ReadAsync().DefaultTimeout()); - Assert.Equal("An unexpected error occurred invoking 'GetClientResult' on the server. Exception: Client error", completion.Error); + Assert.Equal("An unexpected error occurred invoking 'GetClientResult' on the server. HubException: Client error", completion.Error); Assert.Equal(invocationId, completion.InvocationId); } } @@ -381,7 +381,7 @@ public async Task CanCancelClientResultsWithIHubContextT(string protocol) cts.Cancel(); - var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); Assert.Equal("Invocation canceled by the server.", ex.Message); // Sending result after the server is no longer expecting one results in a log and no-ops @@ -426,7 +426,7 @@ public async Task CanCancelClientResultsWithIHubContext() cts.Cancel(); - var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); Assert.Equal("Invocation canceled by the server.", ex.Message); // Sending result after the server is no longer expecting one results in a log and no-ops diff --git a/src/SignalR/server/Specification.Tests/src/HubLifetimeManagerTestBase.cs b/src/SignalR/server/Specification.Tests/src/HubLifetimeManagerTestBase.cs index 426a06ddeebc..e466e844df5f 100644 --- a/src/SignalR/server/Specification.Tests/src/HubLifetimeManagerTestBase.cs +++ b/src/SignalR/server/Specification.Tests/src/HubLifetimeManagerTestBase.cs @@ -220,7 +220,7 @@ public async Task CanProcessClientReturnErrorResult() await manager.SetConnectionResultAsync(connection1.ConnectionId, CompletionMessage.WithError(invocation.InvocationId, "Error from client")).DefaultTimeout(); - var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); Assert.Equal("Error from client", ex.Message); } } @@ -359,7 +359,7 @@ public async Task CanCancelClientResult() var invocation1 = Assert.IsType(await client1.ReadAsync().DefaultTimeout()); cts.Cancel(); - await Assert.ThrowsAsync(() => invoke1).DefaultTimeout(); + await Assert.ThrowsAsync(() => invoke1).DefaultTimeout(); // Noop, just checking that it doesn't throw. This could be caused by an inflight response from a client while the server cancels the token await manager1.SetConnectionResultAsync(connection1.ConnectionId, CompletionMessage.WithResult(invocation1.InvocationId, 1)); diff --git a/src/SignalR/server/Specification.Tests/src/ScaleoutHubLifetimeManagerTests.cs b/src/SignalR/server/Specification.Tests/src/ScaleoutHubLifetimeManagerTests.cs index 610a89be138f..facf0b1c1a38 100644 --- a/src/SignalR/server/Specification.Tests/src/ScaleoutHubLifetimeManagerTests.cs +++ b/src/SignalR/server/Specification.Tests/src/ScaleoutHubLifetimeManagerTests.cs @@ -521,7 +521,7 @@ public async Task CanProcessClientReturnErrorResultAcrossServers() // Server1 gets the result from client1 and forwards to Server2 await manager1.SetConnectionResultAsync(connection1.ConnectionId, CompletionMessage.WithError(invocation.InvocationId, "Error from client")).DefaultTimeout(); - var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); Assert.Equal("Error from client", ex.Message); } } @@ -572,7 +572,7 @@ public async Task ClientDisconnectsWithoutCompletingClientResultOnSecondServer() await manager2.OnDisconnectedAsync(connection1).DefaultTimeout(); // Server should propogate connection closure so task isn't blocked - var ex = await Assert.ThrowsAsync(() => invoke1).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => invoke1).DefaultTimeout(); Assert.Equal("Connection disconnected.", ex.Message); } } @@ -653,7 +653,7 @@ public async Task ClientReturnResultAcrossServersWithWrongReturnedTypeErrors() // Server1 gets the result from client1 and forwards to Server2 await manager1.SetConnectionResultAsync(connection1.ConnectionId, CompletionMessage.WithResult(invocation.InvocationId, "wrong type")).DefaultTimeout(); - var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => resultTask).DefaultTimeout(); Assert.StartsWith("Error trying to deserialize result to Int32.", ex.Message); } } diff --git a/src/SignalR/server/StackExchangeRedis/test/RedisHubLifetimeManagerTests.cs b/src/SignalR/server/StackExchangeRedis/test/RedisHubLifetimeManagerTests.cs index 57827e499c67..1bb22be303d3 100644 --- a/src/SignalR/server/StackExchangeRedis/test/RedisHubLifetimeManagerTests.cs +++ b/src/SignalR/server/StackExchangeRedis/test/RedisHubLifetimeManagerTests.cs @@ -103,7 +103,7 @@ public async Task ErrorFromConnectionFactoryLogsAndAllowsDisconnect() loggerT, Options.Create(new RedisOptions() { - ConnectionFactory = _ => throw new Exception("throw from connect") + ConnectionFactory = _ => throw new ApplicationException("throw from connect") }), new DefaultHubProtocolResolver(new IHubProtocol[] { @@ -113,7 +113,7 @@ public async Task ErrorFromConnectionFactoryLogsAndAllowsDisconnect() { var connection = HubConnectionContextUtils.Create(client.Connection); - var ex = await Assert.ThrowsAsync(() => manager.OnConnectedAsync(connection)).DefaultTimeout(); + var ex = await Assert.ThrowsAsync(() => manager.OnConnectedAsync(connection)).DefaultTimeout(); Assert.Equal("throw from connect", ex.Message); await manager.OnDisconnectedAsync(connection).DefaultTimeout(); diff --git a/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs b/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs index 67a853d8b199..b2d06840e578 100644 --- a/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs +++ b/src/Tools/dotnet-user-jwts/src/Helpers/ConsoleTable.cs @@ -31,12 +31,12 @@ public void AddRow(params string[] values) if (!_columns.Any()) { - throw new Exception("Columns must be set before rows can be added."); + throw new InvalidOperationException("Columns must be set before rows can be added."); } if (_columns.Count != values.Length) { - throw new Exception( + throw new InvalidOperationException( $"The number of columns in the table '{_columns.Count}' does not match the number of columns in the row '{values.Length}'."); }