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 students[roll_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 中的某些错误。

相关推荐
座山雕~4 小时前
Springboot
android·spring boot·后端
韩立学长5 小时前
基于Springboot流浪动物救助系统o8g44kwc(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
我命由我123456 小时前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
小镇学者6 小时前
【other】Goofy Node
后端
颜淡慕潇7 小时前
动态代理赋能:高效爬取沃尔玛海量商品信息与AI分析实战
人工智能·后端
半夏知半秋8 小时前
kcp学习-通用的kcp lua绑定
服务器·开发语言·笔记·后端·学习
hero.fei8 小时前
kaptcha 验证码生成工具在springboot中集成
java·spring boot·后端
w***76558 小时前
存储技术全景:从基础原理到未来趋势
spring boot·后端·mybatis
J_liaty8 小时前
基于ip2region.xdb数据库从IP获取到属地解析全攻略
java·网络·后端
且去填词9 小时前
深入理解 GMP 模型:Go 高并发的基石
开发语言·后端·学习·算法·面试·golang·go