首页 > Python基础教程 >
-
FastAPI 错误处理与自定义错误消息完全指南:构建健壮的 API 应用
第一章:FastAPI 中的错误处理基础
1.1 什么是错误处理?
错误处理是指在应用程序运行过程中,捕获和处理可能发生的错误,确保程序能够优雅地处理异常情况并给出适当的反馈。
1.2 FastAPI 的默认错误响应
FastAPI 提供了内置的错误处理机制,能够自动返回 HTTP 状态码和错误信息。例如,当请求的资源不存在时,会返回 404 错误。
PYTHON
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}
1.3 常见的 HTTP 错误状态码
400 Bad Request:请求参数无效或缺失。
404 Not Found:请求的资源未找到。
422 Unprocessable Entity:请求格式正确,但内容有误。
500 Internal Server Error:服务器内部错误。
第二章:自定义错误消息
2.1 自定义错误响应
您可以通过自定义错误响应来改善用户体验,提供更清晰的错误信息。
PYTHON
from fastapi import Request, FastAPI, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail, "error": "Custom error message"},
)
2.2 示例:使用自定义错误消息
在前面的例子中,如果请求的资源未找到,将返回自定义的错误消息。
PYTHON
@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}
示例请求:
BASH
curl "http://localhost:8000/items/2"
返回:
JSON
{
"detail": "Item not found",
"error": "Custom error message"
}
2.3 处理其他异常
除了 HTTPException,您还可以处理其他类型的异常,例如数据库连接错误。
PYTHON
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"detail": "An unexpected error occurred", "error": str(exc)},
)
第三章:最佳实践
3.1 记录错误
在生产环境中,记录错误信息是非常重要的,可以帮助您排查问题。
PYTHON
import logging
logging.basicConfig(level=logging.INFO)
@app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception):
logging.error(f"Unexpected error: {exc}")
return JSONResponse(
status_code=500,
content={"detail": "An unexpected error occurred"},
)
3.2 课后测验
如何在 FastAPI 中捕获和处理所有未处理的异常?
当请求参数不符合预期时,FastAPI 会返回什么错误?如何自定义这个错误的响应?
提供一个如何避免 SQL 注入攻击的示例。
3.3 常见错误与解决方案
错误:422 Validation Error
原因:请求数据格式不正确或缺失必填字段。
解决方案:检查请求体或查询参数的格式和必填性。
错误:404 Not Found
原因:请求的资源不存在。
解决方案:确认请求的 URL 是否正确,资源是否存在。
错误:500 Internal Server Error
原因:服务器内部错误。
解决方案:检查服务器日志,确认是否存在未处理的异常。
通过本教程,您应该能够掌握 FastAPI 中的错误处理机制和自定义错误消息的技巧,为构建更健壮的 API 应用打下基础。
来源:https://blog.cmdragon.cn/posts/615a966b68d9/