<html>
<body>
<br>
Here's the next challenge in my ongoing quest to write a DBAPI
2.0-compliant abstraction layer.... wrapping exceptions.<br><br>
For this example, let's assume I am using mysqldb as the underlying
driver.<br><br>
<tt>class DriverBase(object):<br><br>
def __init__( self, paramstyle=None ):<br><br>
if paramstyle == None:<br>
self.paramstyle =
'qmark'<x-tab> </x-tab><x-tab> </x-tab><x-tab> </x-tab>#
Default public paramstyle<br>
else:<br>
self.paramstyle = paramstyle<br><br>
import MySQLdb as driver<br><br>
class Driver(DriverBase):<br><br>
name = 'mysqldb'<br><br>
def __init__( self, paramstyle=None ):<br><br>
self._driver =
driver<x-tab> </x-tab><x-tab> </x-tab><x-tab> </x-tab>#
Link to the underlying MySQLdb driver namespace<br>
super(Driver,
self).__init__(paramstyle)<br><br>
self.version =
driver.__version__<br>
self._paramstyle =
driver.paramstyle<x-tab> </x-tab># Underlying private
paramstyle<br>
self.apilevel = driver.apilevel<br>
self.threadsafety
= driver.threadsafety<br><br>
</tt>The next thing I want to do is wrap the DPABI exceptions of the
underlying driver and raise my own equivalents ( which will handle<br>
exception arguments consistently... ) whenever they occur. Here is
the strategy that comes to mind, but I am wondering how the rest of you
might<br>
handle a case like this? <br><br>
# First define our own DBAPI exeptions... this example is limited to only
three for brevity.<br>
<tt>import exceptions<br>
class Error(exceptions.StandardError):<br>
<x-tab> </x-tab>#
DAL-specific stuff<br>
<x-tab> </x-tab>pass<br><br>
class DatabaseError(Error):<br>
<x-tab> </x-tab>#
DAL-specific stuff<br>
<x-tab> </x-tab>pass<br><br>
class InternalError(DatabaseError):<br>
<x-tab> </x-tab>#
DAL-specific stuff<br>
<x-tab> </x-tab>pass<br><br>
</tt>With the exceptions defined, I want to raise them whenever a wrapped
method call raises an exception in the<br>
underlying driver. Here is how I might do this with the connect()
function in the main driver ( this example returns<br>
a Connection object from the underlying driver... the final
implementation will wrap those objects as well. )<br><br>
<tt>def connect( **kwargs ):<br>
<x-tab> </x-tab>try:<br>
<x-tab> </x-tab><x-tab> </x-tab>return
driver.connect(**kwargs)<br>
<x-tab> </x-tab>except
driver.Error, args:<br>
<x-tab> </x-tab><x-tab> </x-tab>raise
Error, args<br>
<x-tab> </x-tab>except
driver.DatabaseError, args:<br>
<x-tab> </x-tab><x-tab> </x-tab>raise
DatabaseError, args<br>
<x-tab> </x-tab>except
driver.InternalError, args:<br>
<x-tab> </x-tab><x-tab> </x-tab>raise
InternalError, args<br><br>
</tt>Is this type of brute-force exception checking around every wrapped
method call necessary or am I missing a much simpler and elegant
solution?<br><br>
Thanks again for everyone's great feedback.<br><br>
<tt><x-tab> </x-tab>Peter
Buschman<br>
</body>
</html>