【问题标题】:how to catch all exceptions raised in flask_restful app如何捕获 flask_restful 应用程序中引发的所有异常
【发布时间】:2018-04-03 01:44:55
【问题描述】:

我确实有一个简单的 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/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"}

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

【问题讨论】:

    标签: python python-3.x flask python-decorators flask-restful


    【解决方案1】:

    有一个 Flask-Restful built-in tool 用于处理异常,您可以将异常类和响应字段的字典传递给 Api 构造函数:

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

    状态默认为 500,所有其他字段都只是转换为 JSON 并作为响应发送。

    有一个主要缺点:您不能将异常文本用作错误消息。有一个open issue

    【讨论】:

      【解决方案2】:

      Sentry 是一个很棒的工具,可以跨不同平台和框架{包括 Python、Django 和 Flask} 捕获异常。 This example 指点您可以将它与您的 Flask 应用程序集成。

      我在生产中使用过它,我最喜欢的功能是它捕获错误的上下文,包括操作系统、浏览器版本等以及其他信息。

      【讨论】:

      • 不错的库。会试试的。但我仍然认为单独使用烧瓶必须是可能的。有什么想法吗?
      猜你喜欢
      • 2010-09-15
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多