首页 > 解决方案 > 猎鹰引发自定义异常json

问题描述

当我加注时,falcon.HTTPNotFound我会关注 JSON

 {
    "title": "404 Not Found",
    "description": {
        "message": "Model mymodel does not exist!",
        "model_id": "mymodel"
    }
}

但我想在下面发送而不是这个

{
   "message": "Model mymodel does not exist!",
   "model_id": "mymodel"
}

我如何在 Falcon 中实现这一目标?

def expect_model_existence(req, resp, resource, params, require_exists):

    model_id = params['model_id']

    if require_exists and not Model.exists(model_id=model_id):
        response = {"message": f"Model {model_id} does not exist!", "model_id": model_id}
        raise falcon.HTTPNotFound(description=response)
    elif not require_exists and Model.exists(model_id=model_id):
        response = {"message": f"Model {model_id} already exists!", "model_id": model_id}
        raise falcon.HTTPConflict(description=response)

定义了一个函数来检查模型的存在并像以前一样应用钩子

@falcon.before(expect_model_existence, True)
    def on_delete(self, req, resp, model_id):
       pass

标签: pythonfalconframework

解决方案


推荐阅读