当具有特定键的对象已经存在时(例如,RethinkDb返回"Duplicated“错误),我试图在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)发布于 2020-09-28 21:05:46
您有一个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这应该可以很好地工作。
https://stackoverflow.com/questions/64102371
复制相似问题