[DB-SIG] Problem with exception classes

Kevin Jacobs jacobs at penguin.theopalgroup.com
Thu Apr 17 14:18:38 EDT 2003


On Thu, 17 Apr 2003, Wichert Akkerman wrote:
> I've been using DB-API2 for a while now but have run into a few issues
> with respect to portability between different SQL backends. One of those
> is the paramstyle, which I'm happy to see might be addressed in DB-API3.
> 
> However issue I ran into is exception classes: a lot of my code is
> passed a database connectino or a cursor and does not know which backend
> it is attached to. However since DB-API2 species that exception types
> can only be accesses directly from the driver module that means I can
> not perform any exception handling. At the moment I work around this
> by using a wrapper that copies the exception classes into the connection
> instance (inspired by the MySQLdb module, which does that as well).
> 
> Is that something that would be useful to add to DB-API3 as well?

I use a trick to virtualize the database exceptions so that I can catch them
without knowing which backend they come from.

class Warning                  (StandardError)       : pass
class Error                    (StandardError)       : pass
class   InterfaceError           (Error)             : pass
class   DatabaseError            (Error)             : pass
class     DataError                (DatabaseError)   : pass
class     OperationalError         (DatabaseError)   : pass
class     IntegrityError           (DatabaseError)   : pass
class     InternalError            (DatabaseError)   : pass
class     ProgrammingError         (DatabaseError)   : pass
class     NotSupportedError        (DatabaseError)   : pass

dbapi_exceptions = [ 'Warning',
                     'Error',
                     'InterfaceError',
                     'DatabaseError',
                     'DataError',
                     'OperationalError',
                     'IntegrityError',
                     'InternalError',
                     'ProgrammingError',
                     'NotSupportedError' ]

def __import_exceptions(module):
  for e in dbapi_exceptions:
    sub_exception    = getattr(module, e)
    global_exception = globals()[e]
    sub_exception.__bases__ += (global_exception,)


import MySQLdb
import pgSQL

__import_exceptions(MySQLdb)
__import_exceptions(pgSQL)

try:
  function_that_calls_into_a_registered_module()

except DataError:
  pass


-Kevin


-- 
--
Kevin Jacobs
The OPAL Group - Enterprise Systems Architect
Voice: (216) 986-0710 x 19         E-mail: jacobs at theopalgroup.com
Fax:   (216) 986-0714              WWW:    http://www.theopalgroup.com




More information about the DB-SIG mailing list