Approaches for Error Code/Message Management in .N

2019-04-28 07:23发布

问题:

Looking for suggestions/best practices on managing error codes and messages in a multi-tiered applications. Specifically things like:

  1. Where should error codes be defined? Enum? Class?
  2. How are error messages or further details associated with the error codes? resource files? attributes on enum values, etc.?
  3. 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!

回答1:

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.



回答2:

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.