Skip to content

Instantly share code, notes, and snippets.

@mitgr81
Last active December 23, 2015 21:59
Show Gist options
  • Save mitgr81/6700430 to your computer and use it in GitHub Desktop.
Save mitgr81/6700430 to your computer and use it in GitHub Desktop.
from flask import make_response
def protect_http_call(func):
"""
Decorator that handles all standard and fall-through exceptions for a REST view. Protect will swallow all exceptions.
Args:
func: Function to be wrapped and protected from raising
Returns:
Wrapper around the passed-in func
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as ex:
code = {
'InvalidFieldsError': 400,
'InvalidContentError': 400,
'AuthorizationError': 401,
'NotFoundError': 404,
}.get(ex.__class__.__name__, 500)
logger.exception(ex)
print(ex.__class__.__name__, ex)
return make_response(str(ex), code)
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment