In our app there's an authentication decorator that checks for user's integrity among other things, we want to handle errors that might occur in the decorator such as invalid user credentials and reply with a json response for that route, what's the best way to go about it?
Asked
Active
Viewed 213 times
1 Answers
1
Here is an example of how to change the return value of the handler inside a decorator:
def auth(handler):
def _wrapped_handler(request):
if not authorised(request):
return jsonify({"status": "forbidden"}), 403
return handler(request)
return _wrapped_handler
@route("/foo/bar")
@auth
def handler(request):
return jsonify({"status": "ok"}), 200
I don't know what conventions you are following, so its possible that e.g. the _wrapped_handler
should accept other arguments, but this is the gist of it.
It helps to remember that
@decorator
def function():
...
is short-hand for
def function():
...
function = decorator(function)
In terms of best practice, a common pattern is to define a general exception handler which converts exceptions into HTTP Responses. See https://flask.palletsprojects.com/en/master/errorhandling/#generic-exception-handlers
If you went down this route, you would raise an appropriate exception in the decorator rather than return a 403 response directly.

Jack Smith
- 336
- 1
- 4