Skip to content

Instantly share code, notes, and snippets.

@danielhfrank
Created June 18, 2013 21:36
Show Gist options
  • Save danielhfrank/5809663 to your computer and use it in GitHub Desktop.
Save danielhfrank/5809663 to your computer and use it in GitHub Desktop.
This decorator is intended to simplify error handling in request cycles with many callbacks. The idea is to decorate a callback function that takes its main "data" as a first positional argument, and a callback as a kwarg called "callback". The decorator will inspect the data argument and attempt to determine if it is an error (either a tornado…
def passthrough_errors(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
callback = kwargs['callback']
data = args[0]
# Check if an error is being passed in, somehow
error = None
if isinstance(data, tornado.httpclient.HTTPResponse) and data.error:
error = data.error
elif isinstance(data, Exception):
error = data
# Short-circuit to the callback if there was an error
if error:
return callback(error)
# try calling the function, and short-circuit on error
try:
method(*args, **kwargs)
except Exception, e:
return callback(e)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment