Approaches for Error Code/Message Management in .NET
Looking for suggestions/best practices on managing error codes and messages in a multi-tier开发者_开发问答ed applications. Specifically things like:
- Where should error codes be defined? Enum? Class?
- How are error messages or further details associated with the error codes? resource files? attributes on enum values, etc.?
- If you have a multi-tier application consisting of DAL, BLL, UI, and Common projects for example, should there be a single giant list of codes for all tiers, or are the codes extensible by project/tier?
Update: Important to mention that I can't rely solely on Exceptions and custom Exception types for error reporting, as some clients for this application will be via web services (SOAP & REST)
Any suggestions welcome!
Error codes are old skool, you needed them back in the bad old days of COM and C programming, environments that didn't support exceptions. Nowadays, you use exceptions to notify client code or the user about problems. Exceptions in .NET are self-descriptive, they have a type, a message and diagnostics.
You need to distinguish two types of exceptions, those that are reasonably recoverable and those where you have no idea what exactly went wrong or how you recover from them. The latter kind is by far the most common, you'll need a human to take corrective action. Use one of the standard built-in .NET exception types to raise them. IllegalOperationException, FormatException, ArgumentException are common choices. If it is the back-end that raises such an exception then you just want to pass it through without altering. You typically need a finally block to ensure your internal state is consistent, sometimes a catch block that contains a simple throw to recover state.
Anything you consider recoverable should be raised with an exception type that you declare yourself, derived from the Exception class. That gives code upstream a chance to write a catch clause and do something meaningful. You'll need to generate a Message that is descriptive of the problem, in case the up-stream code doesn't actually handle it, the text of the message needs to be retrieved from either a hard-coded string or a resource if you support localization.
I think It is better to create a Common Project ( or ApplicationFramework Project ) and put your Exceptions and Common Object on it.
It is always a good idea to have a ApplicationFramework which contains Base Class for your Classes ( specially in UI - PageBase - MasterBase- ModuleBase and etc)
And as its obvious you have to put your classes and Enums in your BLL project.
Note that 3 tier doesn't mean 3 Project. You can have 5 project in your BLL.
Finally don't forget to use ELMAH or any other similar tools.
精彩评论