如何捕获路由装饰器中的错误并以 JSON 响应进行响应

How to catch errors in a route's decorator and respond with a JSON response

在我们的应用程序中有一个身份验证装饰器,用于检查用户的完整性等,我们想要处理装饰器中可能发生的错误,例如无效的用户凭据,并用 json 响应回复该路由,最好的方法是什么?

下面是一个如何在装饰器中更改处理程序的 return 值的示例:

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

我不知道你遵循的是什么约定,所以有可能,例如_wrapped_handler 应该接受其他参数,但这是它的要点。

记住这一点很有帮助

@decorator
def function():
    ...

的简写
def function():
    ...

function = decorator(function)

就最佳实践而言,一种常见的模式是定义一个将异常转换为 HTTP 响应的通用异常处理程序。参见 https://flask.palletsprojects.com/en/master/errorhandling/#generic-exception-handlers

如果你走这条路,你会在装饰器中引发适当的异常,而不是直接 return 403 响应。