我想确保我的错误响应都是有效的JSON,以便我的客户端可以解析它们。 Flask文档提到状态代码404和500是在内部引发的,但是我已经看到一些关于如何返回405的线程。是否有我应该处理的Flask框架的代码列表?
我可以简单地完成并处理所有HTTP状态代码,但对于Flask应用程序来说,这似乎有点苛刻。
@app.errorhandler(500)
def handle500error(error):
return json.dumps(dict(error_message="A serious error occurred.")), 500
或者,是否存在处理其他未处理错误的通用方法?
答案 0 :(得分:2)
使用装饰器无法轻松完成任务,但app对象中有一个易于操作的属性:error_handler_spec
所以,在短时间内做你想做的事就是这样:
from functools import partial
def my_generic_handler(error, code=None):
return json.dumps(dict(error_message="A serious error occurred.")), code
for code in range(400, 600): # All error statuses. And even more but it's ok for the sake of this example
app.error_handler_spec[None][code] = partial(my_generic_handler, code=code)
这是这里发生的事情。 error_handler_spec
是一个dict,第一级是蓝图(None =应用程序),第二级是要处理的代码或错误。
而partial是一个工具,允许您从其他函数声明新函数只馈送部分参数。这样,您就可以为所有状态代码创建通用处理程序,并动态创建特定处理程序。
答案 1 :(得分:1)
我所拥有的是在Flask和Werkzeug中使用HTTP例外的所有地方
$ ls
# We have source code of Flask and Werkzeug in the folder
flask-master werkzeug-master
$ grep -oP "[A-Za-z]+(?=\(HTTPException\))" werkzeug-master/werkzeug/exceptions.py | paste -sd "|" -
# Get a list of HTTP exceptions
BadRequest|Unauthorized|Forbidden|NotFound|MethodNotAllowed|NotAcceptable|RequestTimeout|Conflict|Gone|LengthRequired|PreconditionFailed|RequestEntityTooLarge|RequestURITooLarge|UnsupportedMediaType|RequestedRangeNotSatisfiable|ExpectationFailed|ImATeapot|UnprocessableEntity|PreconditionRequired|TooManyRequests|RequestHeaderFieldsTooLarge|InternalServerError|NotImplemented|BadGateway|ServiceUnavailable|GatewayTimeout|HTTPVersionNotSupported
$ grep -Prn "\b(`!!`)\(" * | grep -Pv "/(tests|docs|examples)/|class "
# Search for these exceptions in source code, but exclude tests, docs, examples and definitions of those exception classes
flask-master/flask/wrappers.py:178: raise BadRequest()
flask-master/flask/helpers.py:586: raise NotFound()
flask-master/flask/helpers.py:590: raise NotFound()
flask-master/flask/helpers.py:625: raise NotFound()
flask-master/flask/app.py:1471: return InternalServerError()
werkzeug-master/werkzeug/utils.py:504: raise BadRequest('The browser failed to transmit all '
werkzeug-master/werkzeug/exceptions.py:20: raise NotFound()
werkzeug-master/werkzeug/serving.py:193: execute(InternalServerError())
werkzeug-master/werkzeug/routing.py:1453: raise MethodNotAllowed(valid_methods=list(have_match_for))
werkzeug-master/werkzeug/routing.py:1454: raise NotFound()
werkzeug-master/werkzeug/formparser.py:185: raise exceptions.RequestEntityTooLarge()
werkzeug-master/werkzeug/formparser.py:218: raise exceptions.RequestEntityTooLarge()
werkzeug-master/werkzeug/formparser.py:359: raise exceptions.RequestEntityTooLarge()
werkzeug-master/werkzeug/contrib/wrappers.py:56: raise BadRequest('Not a JSON request')
werkzeug-master/werkzeug/contrib/wrappers.py:60: raise BadRequest('Unable to read JSON request')
werkzeug-master/werkzeug/contrib/wrappers.py:82: raise BadRequest('Not a Protobuf request')
werkzeug-master/werkzeug/contrib/wrappers.py:88: raise BadRequest("Unable to parse Protobuf request")
werkzeug-master/werkzeug/contrib/wrappers.py:92: raise BadRequest("Partial Protobuf request")