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

相关推荐
微尘81 小时前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
计算机学姐1 小时前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
码拉松2 小时前
千万不要错过,优惠券设计与思考初探
后端·面试·架构
白总Server2 小时前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php
计算机学姐3 小时前
基于python+django+vue的家居全屋定制系统
开发语言·vue.js·后端·python·django·numpy·web3.py
程序员-珍3 小时前
SpringBoot v2.6.13 整合 swagger
java·spring boot·后端
海里真的有鱼4 小时前
好文推荐-架构
后端
骆晨学长4 小时前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
AskHarries4 小时前
利用反射实现动态代理
java·后端·reflect
Flying_Fish_roe5 小时前
Spring Boot-Session管理问题
java·spring boot·后端