Search code examples
c#asp.net-corefxcop

Suppress CA1303 fxcop warning when constructing a new Exception


When I throw an exception in my ASP.NET Core 3.1 code, fxcop warns me when it sees a string literal as an argument to a new Exception(). For example:

throw new InvalidOperationException("Ouch");

gives me CA1303: Do not pass literals as localized parameters

As a general rule, I don't display exception messages to end users, so I have no desire to localize them. Is there a way to configure CA1303 so that it ignores constructor arguments on anything that derives from System.Exception?

EDIT:

After a bit more searching, I've found this conversation about exactly this problem:

https://github.com/dotnet/roslyn-analyzers/issues/2933


Solution

  • Version 3.3.0 of Microsoft.CodeAnalysis.FxCopAnalyzers finally fixed the ability to suppress the warning when calling specific types.

    In order to suppress CA1303 when constructing an Exception or when calling an ILogger function, I added a .editorconfig file to the root directory of my solution (all of the projects are subdirectories of this directory) and added these lines to it:

    [*.cs]
    dotnet_code_quality.CA1303.excluded_type_names_with_derived_types = Exception|LoggerExtensions|ILogger
    

    This tells CA1303 to ignore calls into Exception, LoggerExtensions, and ILogger (and any type that derives from these types).

    For reference, see this issue and the reply beneath it:
    https://github.com/dotnet/roslyn-analyzers/issues/2933#issuecomment-627256340