如何解决FastAPI没有引发HTTPException
当具有特定键的对象已存在时,我试图在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)
解决方法
您有一个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
这应该工作正常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。