在我的应用程序的服务级别,我提出了一个异常,我希望它作为 JSON 打印到浏览器。
我按照文档中的说明实现了它:
raise falcon.HTTPError(
'12345 - My Custom Error',
'some text'
).to_json()
以及控制台的输出:
TypeError: exceptions must derive from BaseException
以前有人遇到过这个问题,可以帮我解决这个问题吗?
你正试图提高一个字符串。正确的方法是使用set_error_serializer()。
文档中的示例似乎正是您所需要的(加上 YAML 支持)。
def my_serializer(req, resp, exception):
representation = None
preferred = req.client_prefers(('application/x-yaml',
'application/json'))
if preferred is not None:
if preferred == 'application/json':
representation = exception.to_json()
else:
representation = yaml.dump(exception.to_dict(),
encoding=None)
resp.body = representation
resp.content_type = preferred
resp.append_header('Vary', 'Accept')
app = falcon.API()
app.set_error_serializer(my_serializer)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句