FastAPI针对错误的处理有以下几种方式:
默认异常处理
使用Exception模块,注意:返回使用raise,而不是return
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {
"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {
"item": items[item_id]}
自定义错误处理Header
此外,对于接口返回还可以添加自定义的Header
@app.get("/items-header/{item_id}")
async def read_item_header