Skip to content

Instantly share code, notes, and snippets.

@sburns
Created February 13, 2013 15:39
Show Gist options
  • Save sburns/4945480 to your computer and use it in GitHub Desktop.
Save sburns/4945480 to your computer and use it in GitHub Desktop.
Proper way to expose exceptions from external libraries

The Issue

One of my packages (redcap) is a service-specific wrapper around the venerable requests. requests exposes the HTTPError exception that is raised e.g. when r.raise_for_status() is called on a 400 response.

Since users of my package might want to catch HTTPErrors, what is the best way to design my API?

Choice 1

from redcap import Project, HTTPError
project = Project(foo, bar)
try:
    project.some_bad_method()
except HTTPError:
    do_something()

Choice 2

from redcap import Project
from requests import HTTPError
try:
    project.some_bad_method()
except HTTPError:
    do_something()

I lean towards 1 because it doesn't require my users to know about requests. Any feedback is appreciated.

@jorendorff
Copy link

Choice 1 for sure, because then your user doesn't have to know or care that you're using requests. Or HTTP for that matter.

But note that HTTPError isn't the only error that can be thrown there. If the server is down, you'll get a ConnectionError; you can also get SSLErrors and so on. So maybe you want to do a little wrapping...?

from redcap import Project, RedcapError

even if redcap.RedcapError is requests.exceptions.RequestException for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment