FastAPI 中的错误处理:如何让错误信息更有价值
创作时间:
作者:
@小白创作中心
FastAPI 中的错误处理:如何让错误信息更有价值
引用
CSDN
1.
https://blog.csdn.net/ylong52/article/details/142261631
在开发API时,错误处理是一个至关重要的环节。良好的错误处理机制不仅能提高API的可用性和可维护性,还能为开发者提供清晰的错误信息,帮助他们快速定位和解决问题。本文将详细介绍如何在FastAPI中实现有效的错误处理策略,包括使用HTTPException、自定义响应模型、JSONResponse、自定义异常处理器以及路由装饰器中的responses参数等方法。
1. 使用HTTPException
当你想要立即返回一个错误响应时,可以直接在路由函数中抛出一个HTTPException,并传入detail参数来提供详细的错误信息。
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id, "value": "Foo"}
2. 自定义响应模型
你可以定义一个Pydantic模型来表示错误响应的结构,并在抛出HTTPException时使用该模型。
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class ErrorModel(BaseModel):
error: str
detail: str
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content=ErrorModel(error=exc.detail, detail=f"An error occurred: {exc.detail}")
)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id, "value": "Foo"}
3. 使用JSONResponse
在路由函数中返回一个JSONResponse对象,并设置状态码和内容。
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
return JSONResponse(status_code=404, content={"error": "Item not found"})
return {"item_id": item_id, "value": "Foo"}
4. 自定义异常处理器
创建一个自定义异常处理器来统一处理异常,并返回详细的错误信息。
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exception_handlers import http_exception_handler
app = FastAPI()
async def custom_http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={
"error": exc.detail,
"detail": "Additional information about the error can be provided here."
}
)
app.add_exception_handler(HTTPException, custom_http_exception_handler)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id, "value": "Foo"}
5. 使用responses参数
在路由装饰器中使用responses参数定义自定义状态码和错误信息。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}", responses={404: {"model": dict, "description": "Item not found"}})
async def read_item(item_id: int):
if item_id != 1:
return {"error": "Item not found"}
return {"item_id": item_id, "value": "Foo"}
通过这些方法,你可以在FastAPI中为自定义错误添加详细的错误信息,从而提供更丰富的错误处理和更好的客户端体验。
热门推荐
如何快速判断工作日与非工作日?实用技巧大公开!
无人机制造工艺流程详解
研究证实:喝饮料真会损害心血管健康,哪怕少喝、运动也都没法补救
学生或遭误判作弊 AI检测工具准确度惹争议
中秋节元素藏品选赏 嫦娥玉兔自古至今受青睐
6条公认的增肌干货,让你增长更多肌肉
水温越高,发病越凶!黄颡鱼“链球菌”高峰死鱼上千条,让你防不胜防
中国证券报头版评论:坚定信心,夯实股市发展基本面支撑
LangChain实战:向量化存储与实际应用案例
夜半湿衣见盗汗,健康警报需细察
商业报告写作指南:要素与效率提升技巧
滑点真相大揭秘:滑点为何让交易者如此厌恶
算命诈骗罪的法律界定与量刑标准
去梵净山需要准备什么东西 十大爬梵净山的装备有哪些
DeepSeek AI大模型全球第三,Meta紧急追加650亿研发投入
冠脉CTA是什么检查
自媒体变现指南:多元路径与成功案例解析
A股、B股、H股、N股、S股是什么意思?
脚后跟痛可能预示哪三种疾病?及早就医是比较佳选择吗?
Word简历中不同字体的影响
轻松get审判流程信息查询大法!四种方式速查案件进展
双非背景也能成功留学?深度剖析不为人知的 8 种留学途径!
软件的压力测试如何做的
华强北二手机:避坑指南与高性价比选购秘诀
“抗炎食物”不是“消炎”!要看这个指数!哪些食物具有抗炎属性呢?
【孩子撒谎】孩子疑似撒谎 家长应该怎么做 8招教你识别和应对孩子的撒谎行为
夫妻多人运动:增进感情的新方式
佩戴隐形眼镜的禁忌
古埃及文字怎么解读?是被谁发现的?
法语学习之交流经验