I'm cleaning up an API library, and trying to figure out the best way to handle unhandled exceptions.
Right now, the library catches just about everything that could go wrong with the API -- credential errors, server errors, urllib2 errors, httplib errors, etc. There will be edge cases.
My current thinking is that 99% of library users don't care about the exception itself, they just care that the API call failed. Only developers would care about the exception.
That leads me to this solution :
class ApiError(Exception):
pass
class ApiUnhandledError(ApiError):
pass
Known issues with the API raise an ApiError or specific subclass.
Everything else raises an ApiUnhandledError , with the original error stashed in, which a user can either catch or ignore.
try:
stuff
except urllib2.UrlError , e :
raise ApiError(raised=e)
except Exception as e :
raise ApiUnhandledError(raised=e)
Does this sound like a good approach to ensuring the users just know a Pass/Fail , while developers can maintain a method of support ?
Update
Based on the consensus of best practices, I won't be trapping this.
The original goal was to allow people to do this:
try:
stuff_a
other_stuff
even_more_stuff
api.proxy(url)
again_stuff
again_others
except api.ApiUnhandledError , e :
handle error
except api.ApiError , e :
handle error
except Stuff , e :
other error
except:
raise
in that example, the user only has to catch ApiError ( and optionally ApiUnhandledError or any of the other subclasses )
i thought this would be largely preferable to every api interaction having its own block :
try:
stuff_a
other_stuff
even_more_stuff
try:
api.proxy(url)
except api.ApiError , e :
handle error
except CatchSomething1 , e :
handle error
except CatchSomething2 , e :
handle error
except CatchSomething3 , e :
handle error
except CatchSomething4 , e :
handle error
except:
raise
again_stuff
again_others
except Stuff , e :
other error
except:
raise
when dealing with urllib2 , i've seem to discover a new exception every day. these exceptions tend to get very long and difficult to maintain.