如何将异常引发为 json?

How to raise exceptions as json?

在我的应用程序的服务级别,我提出了一个异常,我希望它作为 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)

在 falcon 文档中解释了创建自定义异常 class,搜索 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)

将自定义异常 class 添加到 falcon API 对象

api = falcon.API()
api.add_error_handler(RaiseUnauthorizedException)

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

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