1704 字
9 分钟

使用FastAPI的全局异常处理

一、背景

之前我是写Java的,最近刚接触FastAPI,就想知道有没有类似Spring的@ExceptionHandler的全局异常处理,然后就有了这篇文章

二、实现过程

  1. 新建exception_handler.py文件分开分类存放,维护register_exceptions()方法供主程序引用注册即可
    • 注意异常返回类型必须要返回fastapi.responses包的JSONResponse类型
    • 可以创建自定义的异常并进行捕捉,方式和Spring的大差不差,就不多赘述了
# utils/exception_handler.py
from main import logger  
  
from fastapi import Request, FastAPI  
from fastapi.responses import JSONResponse  
from entity.common.response import ResponseModel  
  
def register_exceptions(application: FastAPI):  
    # 全局异常处理  
    @application.exception_handler(Exception)  
    async def global_exception_handler(request: Request, e: Exception):  
        logger.error(f"捕捉到全局异常: {e}", exc_info=True)  
        # 构造响应数据  
        error_response = ResponseModel(  
            code=500,  
            message="服务器内部错误,请稍后再试"  
        )  
  
        # 必须返回 JSONResponse!  
        return JSONResponse(  
            status_code=500,  
            content=error_response.model_dump()  
        )  
  
    @application.exception_handler(ValueError)  
    async def value_error_handler(request: Request, e: ValueError):  
        logger.error(f"捕捉到异常: {e}", exc_info=True)  
        # 构造响应数据  
        error_response = ResponseModel(  
            code=400,  
            message=str(e)  
        )  
  
        # 必须返回 JSONResponse!  
        return JSONResponse(  
            status_code=400,  
            content=error_response.model_dump()  
        )
  1. 在FastAPI主程序中注册即可
# main.py
from fastapi import FastAPI  
from utils.exception_handler import register_exceptions  
  
# 初始化FastAPI应用  
application = FastAPI(lifespan=lifespan)  
  
# 注册异常处理  
register_exceptions(application)

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
使用FastAPI的全局异常处理
https://blog.birenl.top/posts/14/
作者
Jinryu
发布于
2026-02-13
许可协议
CC BY-NC-SA 4.0
最后更新于 2026-02-13,距今已过 36 天

部分内容可能已过时

评论区

目录