我正在尝试使用“Implementing API Exceptions ”页面上的指南在 Flask 1.0.2 和 Flask-RESTful 0.3.7 中创建自定义错误处理程序。 (Flask-RESTful 有自己的 creating custom error messages 方式,但由于它似乎没有办法在异常发生时接受自定义错误消息,因此我尝试使用普通 Flask 方法。)
from flask import Flask, jsonify
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
#########################################
class MyGenericException(Exception):
status_code = 500
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(MyGenericException)
def handle_generic_error(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
#########################################
class TestMe(Resource):
def get(self):
raise MyGenericException('A generic error', status_code=501)
api.add_resource(TestMe, '/testme', endpoint='TestMe')
#########################################
if __name__ == '__main__':
app.run(debug=False)
调用http://127.0.0.1:5000/testme但是,仅返回通用的“500 内部服务器错误”消息,而不是带有我的自定义错误文本的 501 错误。看来MyGenericException
已正确引发,但 Flask 似乎忽略了它。
[2019-05-08 17:09:18,409] ERROR in app: Exception on /testme [GET]
Traceback (most recent call last):
File "C:\Users\testuser\Envs\testenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\testuser\Envs\testenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\testuser\Envs\testenv\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\testuser\Envs\testenv\lib\site-packages\flask\views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "C:\Users\testuser\Envs\testenv\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "C:/Users/testuser/Documents/PyCharm Projects/TestApp/testapp.py", line 32, in get
raise MyGenericException('A generic error', status_code=505)
MyGenericException
@app.errorhandler
装饰器似乎已正确设置为自定义MyGenericException
异常(exception)。为什么 Flask 不处理它?
感谢任何可以提供帮助的人。
最佳答案
引用 this question ,以及 docs ,我从两者中获取的关键信息是,如果您的路线是 Flask-RESTful 路线(您的路线就是),它将由 handle_error()
处理,并且是防止或自定义此情况的唯一方法是实现您自己的API类,并重写handle_error()
。
关于python - 为什么我的 Flask 错误处理程序没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049481/