如何将异常以JSON格式抛出?

3
在我的应用程序服务级别上,我抛出了一个异常,并希望将其作为JSON打印到浏览器中。按照文档说明,我已经实现了它:
raise falcon.HTTPError(
    '12345 - My Custom Error',
    'some text'
).to_json()

控制台输出如下:

TypeError: exceptions must derive from BaseException

有人之前遇到过这个问题并能帮助我吗?
2个回答

3

您正在尝试提高一个字符串。 正确的方法是使用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)

嘿,谢谢你的回答,太棒了:) 我还有一个问题,为什么我需要使用YAML,当每个浏览器都支持JSON并且JSON是首选格式呢?我能不能只写成 "resp.body = exception.to_json()"? - undefined
你不需要它用于浏览器。通常你会用它来满足那些使用Python、PHP等编程语言的高级用户的需求。 - undefined

0
在Falcon文档中解释了如何创建自定义异常类,请搜索add_error_handler。
class RaiseUnauthorizedException(Exception):
    def handle(ex, req, resp, params):
        resp.status = falcon.HTTP_401
        response = json.loads(json.dumps(ast.literal_eval(str(ex))))
        resp.body = json.dumps(response)

将自定义异常类添加到falcon API对象中
api = falcon.API()
api.add_error_handler(RaiseUnauthorizedException)

导入自定义异常类并传递您的消息

message = {"status": "error", "message" : "Not authorized"}
RaiseUnauthorizedException(message)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接