【发布时间】: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)
【问题讨论】: