Error Handling without Exceptions

后端 未结 7 1160
夕颜
夕颜 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:28

    The example you give is of UI validating inputs.

    Therefore, a good approach is to separate the validation from the action. WinForms has a built in validation system, but in principle, it works along these lines:

    ValidationResult v = ValidateName(string newName);
    if (v == ValidationResult.NameOk)
        SetName(newName);
    else
        ReportErrorAndAskUserToRetry(...);
    

    In addition, you can apply the validation in the SetName method to ensure that the validity has been checked:

    public void SetName(string newName)
    {
        if (ValidateName(newName) != ValidationResult.NameOk)
            throw new InvalidOperationException("name has not been correctly validated");
    
        name = newName;
    }
    

    (Note that this may not be the best approach for performance, but in the situation of applying a simple validation check to a UI input, it is unlikely that validating twice will be of any significance. Alternatively, the above check could be done purely as a debug-only assert check to catch any attempt by programmers to call the method without first validating the input. Once you know that all callers are abiding by their contract, there is often no need for a release runtime check at all)

    To quote another answer:

    Either a member fulfills its contract or it throws an exception. Period.

    The thing that this misses out is: What is the contract? It is perfectly reasonable to state in the "contract" that a method returns a status value. e.g. File.Exists() returns a status code, not an exception, because that is its contract.

    However, your example is different. In it, you actually do two separate actions: validation and storing. If SetName can either return a status code or set the name, it is trying to do two tasks in one, which means that the caller never knows which behaviour it will exhibit, and has to have special case handling for those cases. However, if you split SetName into separate Validate and Store steps, then the contract for StoreName can be that you pass in valid inputs (as passed by ValidateName), and it throws an exception if this contract is not met. Because each method then does one thing and one thing only, the contract is very clear, and it is obvious when an exception should be thrown.

    0 讨论(0)
  • 2021-02-05 06:28

    I assume that you are creating your own business rules validation engine, since you haven't mentioned the one you're using.

    I would use exceptions, but I would not throw them. You will obviously need to be accumulating the state of the evaluation somewhere - to record the fact that a particular rule failed, I would store an Exception instance describing the failure. This is because:

    1. Exceptions are serializable
    2. Exceptions always have a Message property that is human-readable, and can have additional properties to record details of the exception in machine-readable form.
    3. Some of the business rules failures may in fact have been signaled by exceptions - a FormatException, for instance. You could catch that exception and add it to the list.

    In fact, this month's MSDN Magazine has an article that mentions the new AggregateException class in .NET 4.0, which is meant to be a collection of exceptions that occurred in a particular context.


    Since you're using Windows Forms, you should use the built-in mechanisms for validation: the Validating event and the ErrorProvider component.

    0 讨论(0)
  • 2021-02-05 06:32

    Exceptions are just that: a way to handle exceptional scenarios, scenarios which should not ordinarily happen in your application. Both examples provided are reasonable examples of how to use exceptions correctly. In both instances they are identifying that an action has been invoked which should not be allowed to take place and is exceptional to the normal flow of the application.

    The misinterpretation is that the second error, the renaming method, is the only mechanism to detect the renaming error. Exceptions should never be used as a mechanism for passing messages to a user interface. In this case, you would have some logic checking the name specified for the rename is valid somewhere in your UI validation. This validation would make it so that the exception would never be part of normal flow.

    Exceptions are there to stop "bad things" happening, they act as last-line-of-defence to your API calls to ensure that errors are stopped and that only legal behaviour can take place. They are programmer-level errors and should only ever indicate one of the following has occured:

    • Something catastrophic and systemic has occurred, such as running out of memory.
    • A programmer has gone and programmed something wrong, be it a bad call to a method or a piece of illegal SQL.

    They are not supposed to be the only line of defence against user error. Users require vastly more feedback and care than an exception will ever offer, and will routinely attempt to do things which are outside of the expected flow of your applications.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2021-02-05 06:38

    I think I'm close to being convinced that throwing exceptions is actually the best course of action for validation type operations, and especially aggregate type operations.

    Take as an example, updating a record in a database. This is an aggregate of many operations that may individually fail.

    Eg.

    1. Check there is a record in the DB to update. -- record may not exists
    2. Validate the fields to be updated. -- the new values may not be valid
    3. Update the database record. -- the db may raise additional errors

    If we are tying to avoid exceptions, we may instead want to use an object that can hold a success or error state:

    public class Result<T> {
      public T Value { get; }
      public string Error { get; }
    
      public Result(T value) => Value = value;
      public Result(string error) => Error = error;
    
      public bool HasError() => Error != null;
      public bool Ok() => !HasError();
    }
    

    Now we can use this object in some of our helper methods:

    public Result<Record> FindRecord(int id) {
      var record = Records.Find(id);
      if (record == null) return new Result<Record>("Record not found");
      return new Result<Record>(record);
    }
    
    public Results<bool> RecordIsValid(Record record) {
      var validator = new Validator<Record>(record);
      if (validator.IsValid()) return new Result<bool>(true);
      return new Result<bool>(validator.ErrorMessages);
    }
    
    public Result<bool> UpdateRecord(Record record) {
      try {
        Records.Update(record);
        Records.Save();
        return new Result<bool>(true);
      }
      catch (DbUpdateException e) {
        new Result<bool>(e.Message);
      }
    }
    

    Now for our aggregate method that ties it all together:

    public Result<bool> UpdateRecord(int id, Record record) {
      if (id != record.ID) return new Result<bool>("ID of record cannot be modified");
    
      var dbRecordResults = FindRecord(id);
      if (dbRecordResults.HasError())
        return new Result<bool>(dbRecordResults.Error);
    
      var validationResults = RecordIsValid(record);
      if (validationResults.HasError())
        return validationResults;
    
      var updateResult = UpdateRecord(record);
      return updateResult;
    }
    

    Wow! what a mess!

    We can take this one step further. We could create subclasses of Result<T> to indicate specific error types:

    public class ValidationError : Result<bool> {
      public ValidationError(string validationError) : base(validationError) {}
    }
    
    public class RecordNotFound: Result<Record> {
      public RecordNotFound(int id) : base($"Record not found: ID = {id}") {}
    }
    
    public class DbUpdateError : Result<bool> {
      public DbUpdateError(DbUpdateException e) : base(e.Message) {}
    }
    

    Then we can test for specific error cases:

    var result = UpdateRecord(id, record);
    if (result is RecordNotFound) return NotFound();
    if (result is ValidationError) return UnprocessableEntity(result.Error);
    if (result.HasError()) return UnprocessableEntity(result.Error);
    return Ok(result.Value);
    

    However, in the above example, result is RecordNotFound will always return false as it is a Result<Record>, whereas UpdateRecord(id, record) return Result<bool>.

    Some positives: * It bascially does works * It avoids exceptions * It returns nice messages when things fail * The Result<T> class can be as complex as you need it to be. Eg, Perhaps it could handle an array of error messages in the case of validation error messages. * Subclasses of Result<T> could be used to indicate common errors

    The negatives: * There are conversion issues where T may be different. eg. Result<T> and Result<Record> * The methods are now doing multiple things, error handling, and the thing they are supposed to be doing * Its extremely verbose * Aggregate methods, such as UpdateRecord(int, Record) now need to concern them selves with the results of the methods they call.

    Now using exceptions...

    public class ValidationException : Exception {
      public ValidationException(string message) : base(message) {}
    }
    
    public class RecordNotFoundException : Exception  {
      public RecordNotFoundException (int id) : base($"Record not found: ID = {id}") {}
    }
    
    public class IdMisMatchException : Exception {
      public IdMisMatchException(string message) : base(message) {}
    }
    
    public Record FindRecord(int id) {
      var record = Records.Find(id);
      if (record == null) throw new RecordNotFoundException("Record not found");
      return record;
    }
    
    public bool RecordIsValid(Record record) {
      var validator = new Validator<Record>(record);
      if (!validator.IsValid()) throw new ValidationException(validator.ErrorMessages)
      return true;
    }
    
    public bool UpdateRecord(Record record) {
      Records.Update(record);
      Records.Save();
      return true;
    }
    
    public bool UpdateRecord(int id, Record record) {
      if (id != record.ID) throw new IdMisMatchException("ID of record cannot be modified");
    
      FindRecord(id);
      RecordIsValid(record);
      UpdateRecord(record);
      return true;
    }
    

    Then in the controller action:

    try {
      UpdateRecord(id, record)
      return Ok(record);
    }
    catch (RecordNotFoundException) { return NotFound(); }
    // ...
    

    The code is waaaay simpler... Each method either works, or raises a specific exception subclass... There are no checks to see if methods succeeded or failed... There are no type conversions with exception results... You could easily add an application wide exception handler that returns the the correct response and status code based on exception type... There are so many positives to using exceptions for control flow...

    I'm not sure what the negatives are... people say that they're like GOTOs... not really sure why that's bad... they also say that the performance is bad... but so what? How does that compare to the DB calls that are being made? I'm not sure if the negatives are really valid reasons.

    0 讨论(0)
  • 2021-02-05 06:43

    I think you've gotten the wrong impression of the intended message. Here's a great quote I ran across yesterday from the current edition of Visual Studio magazine (Vol 19, No 8).

    Either a member fulfills its contract or it throws an excetion. Period. No middle ground. No return codes, no sometimes it works, sometimes it doesn't.

    Exceptions should be used with care as they are expensive to create and throw--but they are, however, the .NET framework's way of notifying a client (by that I mean any calling component) of an error.

    0 讨论(0)
提交回复
热议问题