如何捕获flask_restful应用程序中引发的所有异常

2024-01-12

我确实有简单的 Restful 应用程序与 Flask-Restful

from flask import Flask
from flask_restful import Api

app = Flask(__name__)
...
api = Api(app)

api.add_resource(ContactList, "/contacts")


if __name__ == '__main__':
    from object_SQLAlchemy import db
    db.init_app(app)
    app.run(port=5000)


class Contact(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument(
        'contact_no',
        type=str,
        required=True,
        help="This field cannot be left blank"
    )

    @throttling.Throttle("10/m", strategy=2)
    def get(self, name):
        contact = Contacts.findbyname(name)
        if contact:
            return contact.json()
        return {"message": "Contact does not exist."}, 404

“get”方法用我的节流实现来装饰(https://github.com/scgbckbone/RESTAPI/blob/master/resources/utils/throtdling.py https://github.com/scgbckbone/RESTAPI/blob/master/resources/utils/throttling.py)。重要的是节流装饰器在某些情况下会引发异常 - 最重要的是当达到限制时。我希望能够捕获该异常并返回一些合理的 json 消息。

但以下均不起作用:

from ..app_alchemy import api, app


@api.errorhandler(Exception)
def handle_error(e):
    return {"error": str(e)}


@app.errorhandler(500)
def handle_error_app(e):
    return {"error": str(e.args[0])}


@app.handle_exception(Exception)
def handle_it_app(e):
    return {"error": str(e.args[0])}


@api.handle_exception(Exception)
def handle_it(e):
   return {"error": str(e.args[0])}

我仍然收到默认消息

{"message": "Internal Server Error"}

我是否正确使用错误处理程序,或者问题是否与装饰器的使用有关?我真的不知道。


有一个烧瓶-宁静内置工具 https://flask-restful.readthedocs.io/en/latest/extending.html#define-custom-error-messages为了处理异常,您可以将异常类和响应字段的字典传递给Api构造函数:

api = Api(app, errors={
    'Exception': {
        'status': 400,
        'message': 'bad_request',
        'some_description': 'Something wrong with request'
    }
})

默认情况下,状态为 500,所有其他字段仅转换为 JSON 并作为响应发送。

有一个主要缺点:您不能使用异常文本作为错误消息。有一个开放问题 https://github.com/flask-restful/flask-restful/issues/274 for it.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何捕获flask_restful应用程序中引发的所有异常 的相关文章

随机推荐