Tuesday 10 August 2010

Error checking II

Last month I wrote a blog on why error checking and correction should be documented better and discussed more. In addition the "how" of error checking, it also seems like the "where" to error check can be ill documented and is effected by the tools and frameworks you maybe using.

When designing a function/method one decision that always needs to be made is whether to throw an exception or return a error/default value on an irrecoverable error. The best solution is normally to throw the exception. Returning a default value can make the API more complex, reduces the details about the original error and makes the code difficult to extend and debug. Catching the exception and returning a sensible default value is usually best left to the last point at which you can intercept it. This generally means directly before it hits the user interface.
def myFunction():
"""Allows an errors in doSomething to propagate.
Returns an array or throws an exception."""
return doSomething()

def myDefaultFunction():
"""Returns a default value.
Returns an array.
"""
result = []
try:
result = doSomething()
except StandardError:
pass
return result

A good example of why this can get messy is the MVC architecture pattern. MVC separates the data logic (Model), presentation logic (View) and the Controller which negotiate responses and submissions. The natural place for those pesky unresolved errors is in the View where they can be handled appropriately. The problem occurs because in a lot of frameworks the View is often synonymous with a template that doesn't have the necessary control to handle uncaught exceptions*. So we have to move the logic out, but the View has access to both the Model and the Controller (if it doesn't, it's not MVC) and we don't really want to have to catch exceptions and return default values in the Model. The Model controls the data and is important to the business logic; errors here need to be explicit, not default. So this leaves is with a bit of a mismatch of requirements that can further muddy the waters leading to clear and concise error checking.

* There is a lot of ambiguity in the definition of MVC, but the fact remains that a lot of frameworks explicitly allow the user access to both the View logic, be it template, presentation code, or both, and the Model (context).