| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- from fastapi import FastAPI, Request
- from fastapi import status
- from pydantic_validation_decorator import FieldValidationError
- from core.exceptions import (
- LoginException,
- ServiceWarning,
- ServiceException,
- AuthException,
- ModelValidatorException,
- PermissionException,
- )
- from utils import ResponseUtil, logger
- def add_exception_middleware(app: FastAPI):
- """
- 添加全局异常处理中间件
- 将通用的异常处理逻辑从装饰器中提取出来,提高代码复用性
- """
- @app.middleware("http")
- async def exception_middleware(request: Request, call_next):
- try:
- # 调用下一个中间件或路由处理函数
- response = await call_next(request)
- if response.status_code == status.HTTP_404_NOT_FOUND:
- return ResponseUtil.not_found(request.url.path)
- return response
- except AuthException as e:
- return ResponseUtil.unauthorized(msg=e.message, data=e.data)
- except PermissionException as e:
- return ResponseUtil.forbidden(msg=e.message, data=e.data)
- except (
- LoginException,
- ServiceWarning,
- ModelValidatorException,
- FieldValidationError,
- ) as e:
- # 处理登录异常和服务警告
- logger.warning(e.message)
- return ResponseUtil.failure(msg=e.message, data=e.data)
- except ServiceException as e:
- # 处理服务异常
- logger.error(e.message)
- return ResponseUtil.error(msg=e.message, data=e.data)
- except Exception as e:
- # 处理未预期的异常
- logger.exception(e)
- return ResponseUtil.error(msg=str(e))
|