Fix MA0054 false negative on exceptions of a derived type
Merged
ME
2mo ago+125+125+012345678901234567890123456789-2-2-0123456789
What
MA0054 only reports throw new System.Exception(...). For any other exception type, the operand of the throw is an implicit conversion to System.Exception around the object creation, so the operation.Exception is IObjectCreationOperation check never matches:
try { }
catch (System.Exception ex)
{
throw new System.InvalidOperationException("m"); // expected: MA0054, actual: no diagnostic
}
The code fix also has a bug that this change exposes. When the constructor call uses named arguments that are not in parameter order, the fix inserts a positional argument after them, which doesn't compile:
throw new System.ArgumentException(paramName: "p", message: "m");
// fixed to: new System.ArgumentException(paramName: "p", message: "m", ex) -> CS8323
Fix
- Analyzer: the rule removes the implicit conversions from the thrown expression before it checks for an object creation. This covers
throwstatements andthrowexpressions. - Code fix: when the argument list already contains a named argument, the fix appends a named argument (
innerException: ex). Before, it did this only when the insertion index was past the end of the argument list. - The MA0054 docs now have an example with a derived exception type.
Note: this fixes a false negative, so projects that throw a derived exception from a catch block without the inner exception will get new MA0054 warnings. The docs already describe that case.
Tests
- Added
InCaughtExceptionWithoutInnerException_DerivedException_CodeFix,InCaughtExceptionWithoutInnerException_ThrowExpression_CodeFixandInCaughtExceptionWithoutInnerException_NamedArgumentsOutOfOrder_CodeFix. All 3 failed before the fix, and the named-arguments test still failed with only the analyzer change. - Ran
EmbedCaughtExceptionAsInnerExceptionAnalyzerTestson roslyn5.9 and roslyn4.8: 8/8 passed on each.