chris carter's web log

Home |  Contact |  Admin
 

Validation Exceptions

Posted on September 15, 2008

This one bugs me.  Scott Guthrie has a huge post on some new form stuff that comes with preview 5.  Great info there.  However, looking at the validation examples, you can see that the validation depends on on checking business rules and throwing exceptions if any of the rules fail; then in the controller you catch a general System.Exception, update some stuff for the view, and return the same view.  Why is this bad?

Well, an exception didn't really occur, it was made up because of failing a known business rule.  So basically, now you're using the throwing of exceptions to guide your workflow which makes your code hard to test and hard to follow.  I wouldn't  normally comment on something like this, but I saw another example of this by Stephen Walther here

People, please don't throw exceptions in non-exceptional situations.

Comments

Doug

Can you show an example of how you would do it instead?

 

Chris

@Doug: In the code examples, the business rules are tested with simple if..then logic, and when a business rule fails they are throwing exceptions.  Instead, just check whether all of the rules passed, simple true/false type stuff, if it failed, return the same view like they do in their catch block, if it succeeds, then continue on business as usual.

So something like this:

public ActionResult Edit(Product product){
    ValidationResult result =
        YourBusinessRules.Validate(product);
    if (!result.Success){
        ViewData["errors"] = result.ErrorMessages;
        return View("Edit", product);
    }
    return this.RedirectToAction("index");
}

something like that, i wrote it in notepad so may contain typos, but the difference is now you're not throwing exceptions for an unexceptional situation. 

Now if an unexpected "something" happened inside of the YourBusinessRules class, I would expect an exception to be thrown, because something happened that was unexpected or out of your control.

Post a Comment

(required)
(required)
(no HTML!)