如何捕获flask_restful应用程序中引发的所有异常 [英] how to catch all exceptions raised in flask_restful app

查看:386
本文介绍了如何捕获flask_restful应用程序中引发的所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有一个简单易用的Flask-Restful应用程序

I do have simple restful app with 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消息.

'get' method is decorated with my implementation of throttling (https://github.com/scgbckbone/RESTAPI/blob/master/resources/utils/throttling.py). What is important is that the throttling decorator raises exceptions on some occasions - most importantly when limit is reached. I would like to be able to catch that exception and return some reasonable json message.

但以下任何一项均无效:

But none of following works:

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"}

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

Do I use errorhandlers correctly, or is the issue related to the use of decorator? I truly have no idea.

推荐答案

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

There is a Flask-Restful built-in tool for handling exceptions, you can pass a dictionary of exception classes and response fields to Api constructor:

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

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

Status is 500 by default, all other field are just turned to JSON and sent in response.

有一个主要缺点:您不能将异常文本用作错误消息.有一个未解决的问题.

There is a major downside: you cannot use exception text as error message. There is an open issue for it.

这篇关于如何捕获flask_restful应用程序中引发的所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆