【问题标题】:FastAPI not raising HTTPExceptionFastAPI 没有引发 HTTPException
【发布时间】:2020-09-28 12:39:06
【问题描述】:

当具有特定键的对象已经存在时,我试图在 FastAPI 中引发异常(例如,RethinkDb 返回“重复键”错误)。可能是我的方法逻辑有问题,但无法准确了解。

@router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
def add_brand(brand: Brand):
    with r.connect('localhost', 28015, 'expressparts').repl() as conn:
        try:
            result = r.table("brands").insert({
                "id": brand.id,
                "name": brand.name}).run(conn)
            if result['errors'] > 0:
                error = result['first_error'].split(":")[0]
                raise HTTPException(
                    status_code=400, detail=f"Error raised: {error}")
            else:
                return brand
        except Exception as err:
            print(err)

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    您有一个 try-catch,它会捕获所有发生的错误。您只是在捕获自己的异常,实际上尚未引发。

    @router.post("/brands", response_model=Brand, status_code=status.HTTP_201_CREATED)
    def add_brand(brand: Brand):
        with r.connect('localhost', 28015, 'expressparts').repl() as conn:
            result = r.table("brands").insert({
                "id": brand.id,
                "name": brand.name}).run(conn)
            if result['errors'] > 0:
                error = result['first_error'].split(":")[0]
                raise HTTPException(
                    status_code=400, detail=f"Error raised: {error}")
            else:
                return brand
    

    这应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2021-02-06
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2011-02-12
      • 2022-11-21
      • 2020-08-05
      相关资源
      最近更新 更多