[DB-SIG] Unifying exceptions

M.-A. Lemburg mal at egenix.com
Tue Aug 24 12:42:14 CEST 2004

Ian Bicking wrote:
> There might be a clever/tricky solution that would be a little easier to 
> implement and more reliable.
> Hmm... you could try changing the exceptions, like:
> import psycopg
> psycopg.DatabaseError = MyDatabaseError
> I don't know if this will always stick, or if it's always mutable in 
> this way.  Another way might be:
> class MyDatabaseError(Exception):
>     pass
> psycopg.DatabaseError.__bases__ = (MyDatabaseError,)
> Then you can catch MyDatabaseError, and it will catch 
> psycopg.DatabaseError (since it's a subclass).  This might be more 
> likely to stick, and work better with the C modules.  (Maybe, I don't 
> know...?)

The way I usually cope with this is to bind the module exceptions
to the connection abstraction:

         # Assure that self.Error catches all database related errors.
         if hasattr(module, 'Error'):
             Error = module.Error
         elif hasattr(module, 'error'):
             Error = module.error
             Error = exceptions.StandardError
         self.Error = Error

         # Localize available common constants for database independence
         for symbol in ('InterfaceError',
             obj = getattr(module, symbol, NotGiven)
             if obj is not NotGiven:
                 setattr(self, symbol, obj)
             elif symbol[-5:] == 'Error' or \
                  symbol[-7:] == 'Warning':
                 # All DB-API 2 error classes should be available for
                 # compatibility reasons
                 setattr(self, symbol, Error)

Works great (and is compatible to the DB API 2.0 extension
for connection objects).

Marc-Andre Lemburg

Professional Python Services directly from the Source  (#1, Aug 24 2004)
 >>> Python/Zope Consulting and Support ...        http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::

More information about the DB-SIG mailing list