Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve CA2201: No Reserved Exceptions #47873

Merged
merged 22 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ public ReadOnlyMemory<char> this[int index]
{
get
{
if (index >= count)
{
throw new IndexOutOfRangeException();
}

ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, count);
return count == 1 ? _single : _multiple![index];
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private IJSStreamReference DeserializeJSStreamReference(string serializedStreamR
var jsStreamReference = JsonSerializer.Deserialize<IJSStreamReference>(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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ public KeyValuePair<string, object> this[int index]
{
if (index < 0 || index >= Count)
{
throw new IndexOutOfRangeException(nameof(index));
throw new ArgumentOutOfRangeException(nameof(index));
}

return _values[index];
Expand Down
2 changes: 1 addition & 1 deletion src/Hosting/Hosting/src/Internal/ConfigureBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ internal sealed class HostingRequestFinishedLog : IReadOnlyList<KeyValuePair<str
9 => new KeyValuePair<string, object?>(nameof(request.Path), request.Path.Value),
10 => new KeyValuePair<string, object?>(nameof(request.QueryString), request.QueryString.Value),
11 => new KeyValuePair<string, object?>("{OriginalFormat}", OriginalFormat),
_ => throw new IndexOutOfRangeException(nameof(index)),
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ internal sealed class HostingRequestStartingLog : IReadOnlyList<KeyValuePair<str
7 => new KeyValuePair<string, object?>(nameof(_request.Path), _request.Path.Value),
8 => new KeyValuePair<string, object?>(nameof(_request.QueryString), _request.QueryString.Value),
9 => new KeyValuePair<string, object?>("{OriginalFormat}", OriginalFormat),
_ => throw new IndexOutOfRangeException(nameof(index)),
_ => throw new ArgumentOutOfRangeException(nameof(index)),
};

public HostingRequestStartingLog(HttpContext httpContext)
Expand Down
2 changes: 1 addition & 1 deletion src/Hosting/Hosting/test/ConfigureBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void CapturesServiceExceptionDetails()

var builder = new ConfigureBuilder(methodInfo);
Action<IApplicationBuilder> action = builder.Build(instance: null);
var ex = Assert.Throws<Exception>(() => action.Invoke(applicationBuilder));
var ex = Assert.Throws<InvalidOperationException>(() => action.Invoke(applicationBuilder));

Assert.NotNull(ex);
Assert.Equal($"Could not resolve a service of type '{typeof(CrasherService).FullName}' for the parameter"
Expand Down
2 changes: 1 addition & 1 deletion src/Hosting/TestHost/src/RequestLifetimeFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
2 changes: 1 addition & 1 deletion src/Hosting/TestHost/test/HttpContextBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ public async Task CallingAbortInsideHandlerShouldSetRequestAborted()
});
var server = new TestServer(builder);

var ex = await Assert.ThrowsAsync<Exception>(() => server.SendAsync(c => { }));
var ex = await Assert.ThrowsAsync<OperationCanceledException>(() => server.SendAsync(c => { }));
Assert.Equal("The application aborted the request.", ex.Message);
await requestAborted.Task.DefaultTimeout();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Hosting/TestHost/test/RequestLifetimeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task LifetimeFeature_Abort_TriggersRequestAbortedToken()
});

var client = host.GetTestServer().CreateClient();
var ex = await Assert.ThrowsAsync<Exception>(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead));
var ex = await Assert.ThrowsAsync<OperationCanceledException>(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead));
Assert.Equal("The application aborted the request.", ex.Message);
await requestAborted.Task.DefaultTimeout();
}
Expand All @@ -41,7 +41,7 @@ public async Task LifetimeFeature_AbortBeforeHeadersSent_ClientThrows()
});

var client = host.GetTestServer().CreateClient();
var ex = await Assert.ThrowsAsync<Exception>(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead));
var ex = await Assert.ThrowsAsync<OperationCanceledException>(() => client.GetAsync("/", HttpCompletionOption.ResponseHeadersRead));
Assert.Equal("The application aborted the request.", ex.Message);
abortReceived.SetResult();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public static AuthenticateResult Fail(Exception failure, AuthenticationPropertie
/// <param name="failureMessage">The failure message.</param>
/// <returns>The result.</returns>
public static AuthenticateResult Fail(string failureMessage)
=> Fail(new Exception(failureMessage));
=> Fail(new AuthenticationFailureException(failureMessage));

/// <summary>
/// Indicates that there was a failure during authentication.
Expand All @@ -127,5 +127,5 @@ public static AuthenticateResult Fail(string failureMessage)
/// <param name="properties">Additional state values for the authentication session.</param>
/// <returns>The result.</returns>
public static AuthenticateResult Fail(string failureMessage, AuthenticationProperties? properties)
=> Fail(new Exception(failureMessage), properties);
=> Fail(new AuthenticationFailureException(failureMessage), properties);
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// A generic authentication failure.
/// </summary>
public class AuthenticationFailureException : Exception
{
/// <summary>
/// Creates a new instance of <see cref="AuthenticationFailureException"/>
/// with the specified exception <paramref name="message"/>.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public AuthenticationFailureException(string? message)
: base(message)
{
}

/// <summary>
/// Creates a new instance of <see cref="AuthenticationFailureException"/>
/// with the specified exception <paramref name="message"/> and
/// a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <see langword="null"/>.</param>
public AuthenticationFailureException(string? message, Exception? innerException)
: base(message, innerException)
{
}
}
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public object? this[int index]
get => index switch
{
0 => Arg0,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -85,7 +85,7 @@ public override T GetArgument<T>(int index)
return index switch
{
0 => (T)(object)Arg0!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -130,7 +130,7 @@ public object? this[int index]
{
0 => Arg0,
1 => Arg1,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -198,7 +198,7 @@ public override T GetArgument<T>(int index)
{
0 => (T)(object)Arg0!,
1 => (T)(object)Arg1!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -245,7 +245,7 @@ public object? this[int index]
0 => Arg0,
1 => Arg1,
2 => Arg2,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -318,7 +318,7 @@ public override T GetArgument<T>(int index)
0 => (T)(object)Arg0!,
1 => (T)(object)Arg1!,
2 => (T)(object)Arg2!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -367,7 +367,7 @@ public object? this[int index]
1 => Arg1,
2 => Arg2,
3 => Arg3,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -445,7 +445,7 @@ public override T GetArgument<T>(int index)
1 => (T)(object)Arg1!,
2 => (T)(object)Arg2!,
3 => (T)(object)Arg3!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -496,7 +496,7 @@ public object? this[int index]
2 => Arg2,
3 => Arg3,
4 => Arg4,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -579,7 +579,7 @@ public override T GetArgument<T>(int index)
2 => (T)(object)Arg2!,
3 => (T)(object)Arg3!,
4 => (T)(object)Arg4!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -632,7 +632,7 @@ public object? this[int index]
3 => Arg3,
4 => Arg4,
5 => Arg5,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -720,7 +720,7 @@ public override T GetArgument<T>(int index)
3 => (T)(object)Arg3!,
4 => (T)(object)Arg4!,
5 => (T)(object)Arg5!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -775,7 +775,7 @@ public object? this[int index]
4 => Arg4,
5 => Arg5,
6 => Arg6,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -868,7 +868,7 @@ public override T GetArgument<T>(int index)
4 => (T)(object)Arg4!,
5 => (T)(object)Arg5!,
6 => (T)(object)Arg6!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -925,7 +925,7 @@ public object? this[int index]
5 => Arg5,
6 => Arg6,
7 => Arg7,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -1023,7 +1023,7 @@ public override T GetArgument<T>(int index)
5 => (T)(object)Arg5!,
6 => (T)(object)Arg6!,
7 => (T)(object)Arg7!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -1082,7 +1082,7 @@ public object? this[int index]
6 => Arg6,
7 => Arg7,
8 => Arg8,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -1185,7 +1185,7 @@ public override T GetArgument<T>(int index)
6 => (T)(object)Arg6!,
7 => (T)(object)Arg7!,
8 => (T)(object)Arg8!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down Expand Up @@ -1246,7 +1246,7 @@ public object? this[int index]
7 => Arg7,
8 => Arg8,
9 => Arg9,
_ => new IndexOutOfRangeException()
_ => new ArgumentOutOfRangeException(nameof(index))
};
set
{
Expand Down Expand Up @@ -1354,7 +1354,7 @@ public override T GetArgument<T>(int index)
7 => (T)(object)Arg7!,
8 => (T)(object)Arg8!,
9 => (T)(object)Arg9!,
_ => throw new IndexOutOfRangeException()
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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))
};
}

Expand Down
Loading