错误处理
向客户端返回HTTP错误响应,可以导入HTTPException,HTTPException包含了与API有关数据的常规python异常。
- 只能通过raise捕获
- 触发异常,后续的代码不会再执行
- HTTPException的detail 参数可传递任意能转换为JSON的值
from fastapi import FastAPI, HTTPException
import uvicorn
app = FastAPI()
items = {"zaygee": "zaygee是个大帅哥"}
@app.get("/items")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail={"msg": "not found"})
return {"item": items[item_id]}
if __name__ == "__main__":
uvicorn.run(
app="error_handler:app",
host="127.0.0.1",
port=8080,
reload=True,
debug=True,
log_level="debug",
access_log=True,
use_colors=True
)
自定义异常处理器
通过@app.exception_handler() 添加自定义异常控制器
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn
import pdb
app = FastAPI()
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
# pdb.set_trace()
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
"""
unicorn_exception_handler在服务启动时初始化,fastapi会全局捕获该异常
"""
return JSONResponse(
status_code=518,
content={"message": f"{exc.name} 是自定义异常的名称"}
)
@app.get("/unicorn/{name}")
async def read_unicorn(name: str):
if name == "zaygee":
# pdb.set_trace()
raise UnicornException(name=name) # 异常会被unicorn_exception_handler处理
return {"unicorn_name": name}
if __name__ == "__main__":
uvicorn.run(
app="error_handler:app",
host="127.0.0.1",
port=8080,
reload=True,
debug=True,
log_level="debug",
access_log=True,
use_colors=True
)