exception_middleware.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from fastapi import FastAPI, Request
  2. from fastapi import status
  3. from pydantic_validation_decorator import FieldValidationError
  4. from core.exceptions import (
  5. LoginException,
  6. ServiceWarning,
  7. ServiceException,
  8. AuthException,
  9. ModelValidatorException,
  10. PermissionException,
  11. )
  12. from utils import ResponseUtil, logger
  13. def add_exception_middleware(app: FastAPI):
  14. """
  15. 添加全局异常处理中间件
  16. 将通用的异常处理逻辑从装饰器中提取出来,提高代码复用性
  17. """
  18. @app.middleware("http")
  19. async def exception_middleware(request: Request, call_next):
  20. try:
  21. # 调用下一个中间件或路由处理函数
  22. response = await call_next(request)
  23. if response.status_code == status.HTTP_404_NOT_FOUND:
  24. return ResponseUtil.not_found(request.url.path)
  25. return response
  26. except AuthException as e:
  27. return ResponseUtil.unauthorized(msg=e.message, data=e.data)
  28. except PermissionException as e:
  29. return ResponseUtil.forbidden(msg=e.message, data=e.data)
  30. except (
  31. LoginException,
  32. ServiceWarning,
  33. ModelValidatorException,
  34. FieldValidationError,
  35. ) as e:
  36. # 处理登录异常和服务警告
  37. logger.warning(e.message)
  38. return ResponseUtil.failure(msg=e.message, data=e.data)
  39. except ServiceException as e:
  40. # 处理服务异常
  41. logger.error(e.message)
  42. return ResponseUtil.error(msg=e.message, data=e.data)
  43. except Exception as e:
  44. # 处理未预期的异常
  45. logger.exception(e)
  46. return ResponseUtil.error(msg=str(e))