[英]How to change error format of all errors using Connexion + Tornado
我正在使用 Connexion ( https://github.com/zalando/connexion ) 來確保我的 openapi 規范得到很好的遵循,並有簡單的集成點將我的路由連接到底層功能。
在任何情況下,來自 Connexion 的默認錯誤響應都是遵循HTTP API RFC 問題詳細信息的json 響應。 這是以下格式,例如:
{
"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。
提前致謝。 湯姆
使用最新版本(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
您可以輕松地將其更改為您的格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.