On 5/8/2012 4:05 PM, John Gordon wrote:
I'm trying to come up with a scheme for organizing exceptions in
my application.

Currently, I'm using a base class which knows how to look up the text
of a specific error in a database table, keyed on the error class name.

The base class looks like this:

class ApplicationException(Exception):
     """Base class for application-specific errors."""

     def get_message(self):
         """Return the error message associated with this class name."""

         class_name = self.__class__.__name__
         return UserMessage.objects.get(key=class_name).text

And then I define a bunch of subclasses which all have different names:

class QuestionTooShortError(NetIDAppsError):
     """User entered a security question which is too short."""
     pass

class QuestionTooLongError(NetIDAppsError):
     """User entered a security question which is too long."""
     pass

This scheme works, but I'd like to make it more streamlined.  Specifically,
I'd like to group the classes underneath a parent class, like so:

class Question(ApplicationException):

     class TooShort(ApplicationException):
         pass

     class TooLong(ApplicationException):
         pass

This will make it easier in the future for organizing lots of sub-errors.

I think maybe you are being much too fine-grained in your exception hierarchy. Python has, for instance, just one ValueError, with details in the error. The details can include specific values only known at the point of the error. You are putting some specifics in the exception name and then (apparently) given them somewhat redundant canned messages lacking situation-specific details.

For instance
errfmt = "Security question length {:d} not in legal range {:d} - {:d}"
if not (secquemin <= len(secque) <= secquemax):
  raise ValueError(errfmt.format(len(secque), secquemin, secquemax))
# or ApplicationError or AppValueError if you want.

The messages in Python are not this good, but they slowly improve as people raises an issue on the tracker and others implement and apply fixex.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to