FastAPI 中的错误处理

用于构建 API 的快速且现代的 Python Web 框架称为 FastAPI。与 Python 中的各种实例一样,FastAPI 也可能在执行特定操作时给出一些错误,需要通知用户。在本文中,我们将讨论 FastAPI 中处理错误的各种方法。

FastAPI 中的错误处理是什么?

在构建健壮可靠的应用程序时,错误处理是 Web 开发的一个重要方面。在FastAPI(用于使用 Python 构建 API 的现代 Web 框架)的背景下,理解和实现错误处理对于确保您的 API 优雅地响应各种情况至关重要。

FastAPI 中处理错误的方法

  • 使用 HTTP 状态代码
  • 使用内置异常处理程序
  • 使用自定义异常处理程序
  • 使用中间件
  • 使用日志记录

使用 HTTP 状态代码进行错误处理

FastAPI 为您提供了一些 HTTP 状态代码,为用户提供有关服务器如何处理客户端请求的信息。在此方法中,我们将了解如何使用 HTTP 状态代码处理 FastAPI 中的错误。HTTP 状态代码基本上分为五类:

HTTP消息 状态代码
信息性回应 100-199
成功回应 200-299
重定向消息 300-399
客户端错误响应 400-499
服务器错误响应 500-599

语法: def function_name() -> Item:
if condition:

引发 HTTPException(status_code=HTTP_Code_1,detail=f"error_message_1″)

else:

引发 HTTPException(status_code=HTTP_Code_2,detail=f"error_message_2″)

这里,

  • function_name:这是您在测试时要调用的函数。
  • condition:这是您要添加以返回错误的检查。
  • error_message_1, error_message_2:这些是出现错误时向用户显示的消息。
  • HTTP_Code_1、HTTP_Code_2:这些是我们要与错误消息一起向用户显示的 HTTP 状态代码。

示例:在此示例中,我们通过两个状态代码处理错误,即 200 表示成功,404 表示错误。如果学生列表中存在学号,则显示带有消息的代码 200;如果学生列表中不存在学号,则显示带有消息的代码 404。

python 复制代码
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
	name: str
	roll_number: int

students = {
	1: Student(name="Abhishek", roll_number=1),
	2: Student(name="Ishita", roll_number=2),
	3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
def query_student_by_roll_number(roll_number: int) -> Student:
	if roll_number not in students:
		raise HTTPException(status_code=404, detail=f"Student with {roll_number=} does not exist.")
	else:
		raise HTTPException(status_code=200, detail=f"Student details are as follows: {students[roll_number]}")

输出:调用学生列表中存在的卷号 2 时,显示错误消息如下:

当调用学生列表中不存在的卷号4时,会显示如下错误消息:

FastAPI 中的内置异常处理程序

FastAPI 中的内置异常处理程序使用 HTTP 异常,这是带有一些附加数据的普通 Python 异常。在此方法中,我们将了解如何使用内置异常处理程序处理 FastAPI 中的错误。

语法:def function_name() -> 项目:

if condition:

引发 HTTPException(status_code=HTTP_Code,detail=f"error_message")

这里,

  • function_name:这是您在测试时要调用的函数。
  • condition:这是您要添加以返回错误的检查。
  • error_message:出现错误时向用户显示的消息。
  • HTTP_Code:这是我们要与错误消息一起向用户显示的 HTTP 状态代码。

示例:在此示例中,我们检查学生列表中是否存在学生的学号,然后返回该学生值,否则显示错误消息。

python 复制代码
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel):
	name: str
	roll_number: int
students = {
	1: Student(name="Abhishek", roll_number=1),
	2: Student(name="Ishita", roll_number=2),
	3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
def query_student_by_roll_number(roll_number: int) -> Student:
	if roll_number not in students:
		raise HTTPException(status_code=404, detail=f"Student with {roll_number=} does not exist.")
	return students[roll_number]

输出:调用学生列表中不存在的卷号 4 时,显示错误消息,如下所示:

FastAPI 中的自定义异常处理程序

Python 中处理 Starlette 异常的重要库之一。它还用于引发 FastAPI 中的自定义异常。在此方法中,我们将了解如何使用自定义异常处理程序来处理错误。

语法:

class UnicornException(Exception): def init(self, value: str): self.value = value #Create a custom exception @app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException): return JSONResponse(status_code=404, content={"message": f"error_message"}, ) async def function_name(roll_number: int): if condition: raise UnicornException(value=condition_value)

这里,

  • function_name:这是您在测试时要调用的函数。
  • condition:这是您要添加以返回错误的检查。
  • error_message:出现错误时向用户显示的消息。
  • condition_value:这是需要检查条件的值。

示例:在此示例中,我们检查学生列表中是否存在学生的学号,然后返回该学生值,否则显示错误消息。

python 复制代码
from fastapi import FastAPI, Request
from pydantic import BaseModel
from fastapi.responses import JSONResponse
app = FastAPI()
class UnicornException(Exception):
	def __init__(self, value: str):
		self.value = value
class Student(BaseModel):
	name: str
	roll_number: int
students = {
	1: Student(name="Abhishek", roll_number=1),
	2: Student(name="Ishita", roll_number=2),
	3: Student(name="Vinayak", roll_number=3),
}
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
	return JSONResponse(
		status_code=404,
		content={"message": f"Student with particular roll number does not exist."},
	)
@app.get("/items/{roll_number}")
async def read_unicorn(roll_number: int):
	if roll_number not in students:
		raise UnicornException(value=roll_number)
	return students[roll_number]

输出

当调用学生列表中不存在的卷号4时,会显示如下错误消息:

FastAPI 中的中间件

FastAPI 中在处理每个请求之前对其进行处理的函数称为中间件。在此方法中,我们将了解如何使用中间件处理 FastAPI 中的错误。

语法:app.add_middleware(GZipMiddleware)

async def function_name():

if condition:

return (f"error_message")

这里,

  • function_name:这是您在测试时要调用的函数。
  • condition:这是您要添加以返回错误的检查。
  • error_message:出现错误时向用户显示的消息。

示例:在此示例中,我们检查学生列表中是否存在学生的学号,然后返回该学生值,否则显示错误消息。

python 复制代码
from fastapi import FastAPI, Request
from pydantic import BaseModel
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware)
class Student(BaseModel):
	name: str
	roll_number: int
students = {
	1: Student(name="Abhishek", roll_number=1),
	2: Student(name="Ishita", roll_number=2),
	3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
async def query_student_by_roll_number(roll_number: int):
	if roll_number not in students:
		return (f"Student with {roll_number=} does not exist.")
	return students[roll_number]

输出

当调用学生列表中不存在的卷号4时,会显示如下错误消息:

登录 FastAPI

关键的功能集,例如 debug、catch 是由 Python 中的日志记录提供的。在此方法中,我们将了解如何使用日志记录处理 FastAPI 中的错误。

语法 :logger =logging.getLogger(name)

async def function_name():

try:

if condition:

return (f"error_message")

return studentsroll_number

except Exception as e:

logger.exception(e)

raise HTTPException(status_code=500, detail="Internal server error")

在这里

  • function_name:这是您在测试时要调用的函数。
  • condition:这是您要添加以返回错误的检查。
  • error_message:出现错误时向用户显示的消息。

示例:在此示例中,我们检查学生列表中是否存在学生的学号,然后返回该学生值,否则显示错误消息。

python 复制代码
from fastapi import FastAPI, Request, HTTPException
from pydantic import BaseModel
import logging
app = FastAPI()
logger = logging.getLogger(__name__)
class Student(BaseModel):
	name: str
	roll_number: int
students = {
	1: Student(name="Abhishek", roll_number=1),
	2: Student(name="Ishita", roll_number=2),
	3: Student(name="Vinayak", roll_number=3),
}
@app.get("/items/{roll_number}")
async def query_student_by_roll_number(roll_number: int):
	try:
		if roll_number not in students:
			return (f"Student with {roll_number=} does not exist.")
		return students[roll_number]
	except Exception as e:
		logger.exception(e)
	raise HTTPException(status_code=500, detail="Internal server error")

输出

当调用学生列表中不存在的卷号4时,会显示如下错误消息:

总结:

我们的职责不是阻止用户执行可能引发错误的特定操作,而是处理这些错误,以便用户知道他们做错了什么。本文中定义的众多方法将帮助您处理 FastAPI 中的某些错误。

相关推荐
CaffeinePro5 分钟前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
Chenyiax36 分钟前
从 Chat 到 Responses:OpenAI API 抽象为什么变了?
后端
MariaH37 分钟前
Koa和Express的区别
后端
MariaH43 分钟前
Koa框架的使用
后端
luckdewei2 小时前
那个用 passlib 做认证的新同事,上线第一天就把用户密码写进了日志
后端
ping某3 小时前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx
JustHappy3 小时前
我汇总了身边朋友的经历才发现,其实第一份实习是最难找的......
前端·后端·面试
uhakadotcom3 小时前
在python 的 工程化架构中 ,什么是 薄包装器层?
后端·面试·github
用户1474853079748 小时前
CodeX使用Skill生成游戏美术和音乐资源,一分钟入门
后端
Melody1238 小时前
用 abort 中断 AI 流式请求,我之前做错了
后端