我正在尝试在具有特定键的对象已经存在时(例如RethinkDb返回“重复键”错误)在FastAPI中引发异常。我的方法逻辑可能出了点问题,但无法准确获得。
@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,它捕获了所有发生的错误。您只是在捕获自己的Exception,实际上尚未引发它。
@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
这应该工作正常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句