我正在尝试将所有错误作为JSON返回给我的webservice。我找到了以下代码段:http://flask.pocoo.org/snippets/83/,它描述了实现此方法的方法。当我尝试使用它时,我得到以下堆栈跟踪
127.0.0.1 - - [30/Oct/2016 00:27:57] "GET /401 HTTP/1.1" 500 -
Traceback (most recent call last):
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1559, in handle_exception
handler = self._find_error_handler(InternalServerError())
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1476, in _find_error_handler
.get(code))
File "/opt/thermostat/python/venv/lib/python2.7/site-packages/flask/app.py", line 1465, in find_handler
handler = handler_map.get(cls)
AttributeError: 'function' object has no attribute 'get'
使用此示例应用的源代码:https://github.com/domenicosolazzo/flask_examples/blob/master/json-oriented-app_example.py。免责声明:这不是我的代码,而是我提取的样本,但我得到了同样的错误。
我需要将所有错误作为JSON而不是Flask默认的HTML返回。有没有更好的方法来做我想要的?
答案 0 :(得分:2)
我刚刚遇到了同样的问题,发现新版本的Flask引入了这个问题。从此commit找到此变通方法,只需替换以下错误处理程序分配:
app.error_handler_spec[None][error_code] = function
通过
app.register_error_handler(error_code, function)