wrapper api / proxying third party exception?

dieter dieter at handshake.de
Wed Dec 16 02:48:03 EST 2015


Benjamin Risher <brisher777 at gmail.com> writes:
> Ok, here's my issue.  I have a plugin framework I wrote that relies on a third party library that I can't change.  As a part of that framework, I wrote a small stub library to proxy calls to the third party library, so that if their api ever changes, plugins written against the stub won't have to change, I'll just have to update the back-half that interfaces with the library.  I think this is called an adapter design pattern...?  
>
> plugin --> my api --> their api --> their library 
>
> It works, for the most part.  Most of my classes look similar to this
>
>     class MYClass:
>         def __init__(self, *args, **kwargs):
>             self.__theirclass = TheirClass(*args, **kwargs)
>
>         def __getattr__(self, attr):
>             return getattr(self.__theirclass, attr)
>
> What I'm having issue with, is their exception class.  
>
> 1.  A plugin calls a stub in my library
> 2.  That stub calls the corresponding call in the third party library
> 3.  The call raises an exception from the library
> 4.  The plugin can't catch the exception without importing directly from the third party library
>
> What is the correct way to allow plugins to import my stub exception, but catch the ones raised by the library?

I would approach this as follows:

 * define an exception hiearchy for your wrapper with a common root class
   and document those hiearchy to be used for the plugins

 * in your wrapper, catch all exceptions

   - if it is one of your execptions, you know what to do

   - if it is a general Python exception, it likely indicates
     a programming error in the plugin or library -- handle
     as appropriately (personally, I would "reraise")

   - if it is something else, it likely indicates that
     the plugin violated its contract (towards your wrapper API) --
     handle as appropriate (again, I would "reraise").




More information about the Python-list mailing list