Error Handling without Exceptions

后端 未结 7 1162
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 06:43

    I agree part of Henk's suggestion.

    Traditionally, "pass/fail" operations were implemented as functions with an integer or bool return type that would specifiy the result of the call. However, some are opposed to this, stating that "A function or method should either perform an action or return a value, but not both." In otherwords, a class memeber that returns a value should not also be a class memeber that changes the state of the object.

    I've found the best solution to add a .HasErrors/.IsValid and an .Errors property within the class that generates the errors. The first two properties allow the client class to test wether or not errors exist, and if need be, can also read the .Errors property and report one or all of the errors contained. Each method then must be aware of these properties and manage the error state appropriately. These properties can then be rolled into an IErrorReporting interface that various business rule layer facade classes can incorporate.

提交回复
热议问题