Python 如何使用Connexion+;更改所有错误的错误格式;龙卷风
我使用Connexion()来确保我的openapi规范得到了很好的遵循,并且有了简单的集成点来将我的路由连接到底层函数 在任何情况下,Connexion的默认错误响应都是RFC后面的json响应。即以下格式,例如:Python 如何使用Connexion+;更改所有错误的错误格式;龙卷风,python,flask,error-handling,connexion,Python,Flask,Error Handling,Connexion,我使用Connexion()来确保我的openapi规范得到了很好的遵循,并且有了简单的集成点来将我的路由连接到底层函数 在任何情况下,Connexion的默认错误响应都是RFC后面的json响应。即以下格式,例如: { "detail": "None is not of type 'object'", "status": 404, "title": "BadRequest", "type": "about:blank" } 但是,我想将发送的所有错误的格式更改
{
"detail": "None is not of type 'object'",
"status": 404,
"title": "BadRequest",
"type": "about:blank"
}
但是,我想将发送的所有错误的格式更改为:
{
error: {
code: 400,
message: 'BadRequest',
detail: 'ID unknown'
innererror: {...}
}
}
我找不到任何方法截获每个错误以更改返回内容的格式。我知道我可以扩展connection.exception.ProblemException
类,并在其构造函数的ext
参数中添加一个dict,但是对于任何400
错误,例如,我无法截获它
因此,我知道可以为特定错误代码添加错误处理程序,例如:
app.add_error_handler(404, error.normalize)
app.add_error_handler(400, error.normalize)
但是,对于404
处理程序,我成功地截获了错误。但是对于400
(例如,json验证错误)-拦截不起作用
我如何截获从Connexion发送的每个错误并更改json格式,即使只是为了扩展它,如:
{
"detail": "Could not find page",
"error": {
"code": 404,
"message": "Could not find requested document."
},
"status": 404,
"title": "NotFound",
"type": "about:blank"
}
我使用Connexion和“tornado”服务器
提前谢谢。
Tom拥有最新版本(connexion==2.5.1),这对我来说很有用:
from connexion import ProblemException
[...]
connexion_app.add_error_handler(400, render_http_exception)
connexion_app.add_error_handler(404, render_http_exception)
connexion_app.add_error_handler(ProblemException, render_problem_exception)
我的异常处理功能:
from flask import jsonify
def render_http_exception(error):
resp = {
'error': {
'status': error.name,
'code': error.code,
'message': error.description,
}
}
return jsonify(resp), error.code
def render_problem_exception(error):
resp = {
'error': {
'status': error.title,
'code': error.status,
'message': error.detail,
}
}
return jsonify(resp), error.status
您可以轻松地将其更改为您的格式