Error Handling without Exceptions

后端 未结 7 1263
夕颜
夕颜 2021-02-05 06:02

While searching SO for approaches to error handling related to business rule validation, all I encounter are examples of structured exception handling.

MSDN and many oth

7条回答
  •  花落未央
    2021-02-05 06:36

    In my opinion, if in doubt, throw exceptions on business rule validation. I know this is somewhat counter-intuitive and I may get flamed for this, but I stand by it because what is routine and what is not depends on the situation, and is a business decision, not a programming one.

    For example, if you have business domain classes that are used by a WPF app and a WCF service, invalid input of a field may be routine in a WPF app, but it would be disastrous when the domain objects are used in a WCF situation where you are handling service requests from another application.

    I thought long and hard, and came up with this solution. Do the following to the domain classes:

    • Add a property: ThrowsOnBusinessRule. Default should be true to throw exceptions. Set it to false if you don't want to throw it.
    • Add a private Dictionary collection to store exceptions with key as domain property that has business rule violation. (Of course, you can expose this publicly if you want)
    • Add a method: ThrowsBusinessRule(string propertyName, Exception e) to handle tho logic above
    • If you want, you can implement IDataErrorInfo and use the Dictionary collection. Implementation of IDataErrorInfo is trivial given the setup above.

提交回复
热议问题