错误处理

向客户端返回HTTP错误响应,可以导入HTTPException,HTTPException包含了与API有关数据的常规python异常。

  1. 只能通过raise捕获
  2. 触发异常,后续的代码不会再执行
  3. HTTPException的detail 参数可传递任意能转换为JSON的值
  1. from fastapi import FastAPI, HTTPException
  2. import uvicorn
  3. app = FastAPI()
  4. items = {"zaygee": "zaygee是个大帅哥"}
  5. @app.get("/items")
  6. async def read_item(item_id: str):
  7. if item_id not in items:
  8. raise HTTPException(status_code=404, detail={"msg": "not found"})
  9. return {"item": items[item_id]}
  10. if __name__ == "__main__":
  11. uvicorn.run(
  12. app="error_handler:app",
  13. host="127.0.0.1",
  14. port=8080,
  15. reload=True,
  16. debug=True,
  17. log_level="debug",
  18. access_log=True,
  19. use_colors=True
  20. )

image.png
image.png

自定义异常处理器

通过@app.exception_handler() 添加自定义异常控制器

  1. from fastapi import FastAPI, Request
  2. from fastapi.responses import JSONResponse
  3. import uvicorn
  4. import pdb
  5. app = FastAPI()
  6. class UnicornException(Exception):
  7. def __init__(self, name: str):
  8. self.name = name
  9. # pdb.set_trace()
  10. @app.exception_handler(UnicornException)
  11. async def unicorn_exception_handler(request: Request, exc: UnicornException):
  12. """
  13. unicorn_exception_handler在服务启动时初始化,fastapi会全局捕获该异常
  14. """
  15. return JSONResponse(
  16. status_code=518,
  17. content={"message": f"{exc.name} 是自定义异常的名称"}
  18. )
  19. @app.get("/unicorn/{name}")
  20. async def read_unicorn(name: str):
  21. if name == "zaygee":
  22. # pdb.set_trace()
  23. raise UnicornException(name=name) # 异常会被unicorn_exception_handler处理
  24. return {"unicorn_name": name}
  25. if __name__ == "__main__":
  26. uvicorn.run(
  27. app="error_handler:app",
  28. host="127.0.0.1",
  29. port=8080,
  30. reload=True,
  31. debug=True,
  32. log_level="debug",
  33. access_log=True,
  34. use_colors=True
  35. )

image.png