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

相关推荐
ai小鬼头22 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.28 分钟前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿1 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年2 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱2 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
一只叫煤球的猫2 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
旷世奇才李先生2 小时前
Ruby 安装使用教程
开发语言·后端·ruby
沃夫上校5 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务
LeeGe5 小时前
SpringAOP中@within和@annotation以及 @within和@target的区别
后端