Skip to content

Instantly share code, notes, and snippets.

@girol
Created July 20, 2022 20:39
Show Gist options
  • Save girol/bc33ca4c207a1886a264ec3773a5fcfc to your computer and use it in GitHub Desktop.
Save girol/bc33ca4c207a1886a264ec3773a5fcfc to your computer and use it in GitHub Desktop.
exception_decorator
from functools import wraps
from marshmallow import ValidationError
from mensageria.backends.exceptions import BackendException
from mensageria.core.exceptions import (
BackendNotFoundException,
ConfigurationNotFoundException,
)
def exception_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
response = func(*args, **kwargs)
except (BackendNotFoundException, ValidationError) as e:
error_msg = e.args[0]
return {"error": error_msg}, 400
except (ConfigurationNotFoundException, NotImplementedError) as e:
error_msg = e.args[0]
return {"error": error_msg}, 500
except BackendException as e:
response = {
"backend": e.backend,
"error": e.args[0],
"backend_response": e.response,
}
return response, e.status_code
return response
wrapper._decorator_name = "exception_handler"
return wrapper
from mensageria.core.blueprints import MensageriaBlueprint
from mensageria.utils.api import exception_handler
app = MensageriaBlueprint("message", __name__)
@app.route("/v1/messages", methods=["POST"])
@exception_handler
def message():
payload = app.validate_payload()
response = app.backend.send(payload)
return response, 201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment