FastAPI 没有引发 HTTPException

FastAPI not raising HTTPException

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

@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)

你有一个 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

这应该没问题。