fastapi: 第十章:自定义业务错误码(ErrorCode 枚举)
一,自定义业务错误码的好处?
规范的业务错误码(Business Error Code)是前后端高效协同的核心。
使用 Python 的 Enum 来统一管理错误码,可以避免代码中出现“魔术数字(Magic Numbers)”,
并且让前端能够根据错误码做精准的页面提示或跳转。
二,自定义业务错误码
代码:
# app/core/constants/ErrorCode.py
from enum import Enum
class ErrorCode(Enum):
"""业务状态码枚举"""
# --- 1xxxx 通用系统错误 ---
SUCCESS = (200, "操作成功")
SYSTEM_ERROR = (500, "系统内部错误,请稍后再试")
PARAM_ERROR = (422, "请求参数校验失败")
NOT_FOUND = (404, "请求资源不存在")
# --- 2xxxx 用户与认证模块 ---
TOKEN_EXPIRED = (20001, "登录已过期,请重新登录")
TOKEN_INVALID = (20002, "无效的身份凭证")
USER_NOT_FOUND = (20003, "用户不存在")
PASSWORD_ERROR = (20004, "用户名或密码错误")
USER_DISABLED = (20005, "该账户已被禁用")
def __init__(self, code: int, msg: str):
self.code = code
self.msg = msg
调用
# api/auth.py
from fastapi import APIRouter, Form
from pydantic import BaseModel
from app.core.BusinessException import BusinessException
from app.core.ErrorCode import ErrorCode
from app.utils.response import success
router = APIRouter(prefix="/account", tags=["登录验证"])
@router.post("/login")
def get_all_products(user_id: int = Form(...), user_name: str = Form(...)):
if user_id == 123: # 例如用户状态被锁定
# raise BusinessException(code=10001, msg="当前用户状态错误")
raise BusinessException(code = ErrorCode.USER_NOT_FOUND.code,msg=ErrorCode.USER_NOT_FOUND.msg)
user_info = {"id": user_id, "name": f"用户{user_name}"}
return success(data=user_info)
三,测试效果:

四,说明:也可以直接传递业务错误码给BusinessException,
这样可以对错误代码实现更强的约束
浙公网安备 33010602011771号