How to: Suppress FxCop messages in code
You all know the problem. You run FxCop on your project or solution and it keeps throwing messages at you that for some reason you want to ignore for this project. Say you're building a WinForms application and in the click event for your button, you want to catch all exceptions and display a message to the user. FxCop will show you the message "Do not catch general exception types". And the details for that message are even more specific:
You should not catch Exception or SystemException. Catching generic exception types can hide run-time problems from the library user, and can complicate debugging. You should catch only those exceptions that you can handle gracefully.
Now as a rule, I think FxCop is right. But at some point you will have to do something with these exceptions. You may want to to write them to an error log so that you can actually solve the problem that the application encountered. Or perhaps you want to display a really cool message to your user.
Until now, you had the following options to make sure these rules no longer showed when you ran FxCop:
- Right-click the message in FxCop and choose Exclude.
- Go to the Rules tab in FxCop, find the rule and clear the checkbox.
As of release 1.35, you now have another option. You can add the SuppressMessage attribute to the code and tell FxCop to ignore the message for that method or class. I think this has some advantages over the previous options.
- It is clear in the code that certain code analysis problems are ignored. You can even add comments as to why.
- The other options depend on an FxCop project where the selections are stored. If that project's gone, so is the suppression. And when a another developer runs FxCop on that code again, he or she will have to rethink if the message is valid or not.
One snag, it will only work in Visual Studio 2005. So how would you go about and use this option if you're a C# developer:
- In Solution Explorer, right-click your project and choose Properties.
- In the Properties window, choose the Build tab.
- In the Conditional compilation symbols text box, enter CODE_ANALYSIS.
- In the code where you want to suppress certain messages, add the namespace System.Diagnostics.CodeAnalysis to the using section.
- In FxCop, right-click the message you want to suppress and select Copy As -> SuppressMessage.
- In your C# code, paste the SuppressMessage attribute in your code.
Needless to say that this works with all rules FxCop will apply to your code. It works in VB.Net or C++ as well. How you would go about and do it in those languages can be found here. Visual Studio Managed Code Analysis (FxCop) blog.