我在应用程序中使用以下错误处理程序:def make_json_error(ex):
status_code = ex.code if isinstance(ex, HTTPException) else 500
description = str(ex.description) if isinstance(ex, HTTPException) else 'internal server error'
message = {'error': {'message': '{}: {}'.format(str(status_code), description)}}
response = jsonify(message)
response.status_code = status_code
return response
然后在创建烧瓶应用程序时使用:
^{pr2}$
奇怪的是,对于某些无效请求,它不会返回JSON格式的错误:$ curl 'http://127.0.0.1:5000/api/tickets?id=a' -H "Content-Type: application/json"
{
"error": {
"message": "400: Invalid id parameter values"
}
}
$ curl 'http://127.0.0.1:5000/api/tickets?id=a 1' -H "Content-Type: application/json"
/p>
"http://www.w3.org/TR/html4/strict.dtd">
Error responseError response
Error code: 400
Message: Bad request syntax ('GET /api/tickets?id=a 1 HTTP/1.1').
Error code explanation: 400 - Bad request syntax or unsupported method.
注意第二个命令中查询字符串中的额外空格。你知道为什么这也不被当作400错误来处理,和第一个错误一样?据我所知,第二个URL甚至没有通过/tickets视图函数进行路由,所以我假设空格在Flask中以某种方式进行了特殊解释。在