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

相关推荐
小咕聊编程1 小时前
【含文档+源码】基于SpringBoot的过滤协同算法之网上服装商城设计与实现
java·spring boot·后端
追逐时光者7 小时前
推荐 12 款开源美观、简单易用的 WPF UI 控件库,让 WPF 应用界面焕然一新!
后端·.net
Jagger_7 小时前
敏捷开发流程-精简版
前端·后端
苏打水com8 小时前
数据库进阶实战:从性能优化到分布式架构的核心突破
数据库·后端
间彧9 小时前
Spring Cloud Gateway与Kong或Nginx等API网关相比有哪些优劣势?
后端
间彧9 小时前
如何基于Spring Cloud Gateway实现灰度发布的具体配置示例?
后端
间彧9 小时前
在实际项目中如何设计一个高可用的Spring Cloud Gateway集群?
后端
间彧9 小时前
如何为Spring Cloud Gateway配置具体的负载均衡策略?
后端
间彧9 小时前
Spring Cloud Gateway详解与应用实战
后端
EnCi Zheng10 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端