Skip to content

Instantly share code, notes, and snippets.

@Schandlich
Created April 11, 2014 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Schandlich/10489645 to your computer and use it in GitHub Desktop.
Save Schandlich/10489645 to your computer and use it in GitHub Desktop.
[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer(DiagnosticId, LanguageNames.CSharp)]
public class DiagnosticAnalyzer : ISyntaxNodeAnalyzer<SyntaxKind>
{
internal const string DiagnosticId = "DoNotThrowCaughtException";
internal const string Description = "Do not throw back a caught exception like this.";
internal const string MessageFormat = "Really? REALLY?!";
internal const string Category = "Usage";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);
public ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get { return ImmutableArray.Create(Rule); }
}
public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest
{
get { return ImmutableArray.Create(SyntaxKind.CatchDeclaration); }
}
public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
var catchDeclaration = (CatchDeclarationSyntax)node;
var catchDeclarationIdentifier = catchDeclaration.Identifier;
var exceptionIdentifier = catchDeclarationIdentifier.Text;
var throwStatements = catchDeclaration.Parent.DescendantNodes()
.OfType<ThrowStatementSyntax>()
.Where(c => c.Expression != null && c.Expression is IdentifierNameSyntax && ((IdentifierNameSyntax)c.Expression).Identifier.ValueText == exceptionIdentifier);
foreach (var throwStatement in throwStatements)
{
addDiagnostic(Diagnostic.Create(Rule, throwStatement.GetLocation()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment