__init__.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from fastapi import FastAPI, Request
  2. from fastapi.encoders import jsonable_encoder
  3. from fastapi.exceptions import HTTPException
  4. from pydantic_validation_decorator import FieldValidationError
  5. from starlette.responses import JSONResponse
  6. from core.exceptions import (
  7. AuthException,
  8. LoginException,
  9. ModelValidatorException,
  10. PermissionException,
  11. ServiceException,
  12. ServiceWarning,
  13. )
  14. from utils import ResponseUtil, logger
  15. def handle_exception(app: FastAPI):
  16. """
  17. 全局异常处理
  18. """
  19. # 自定义token检验异常
  20. @app.exception_handler(AuthException)
  21. async def auth_exception_handler(_: Request, exc: AuthException):
  22. return ResponseUtil.unauthorized(data=exc.data, msg=exc.message)
  23. # 自定义登录检验异常
  24. @app.exception_handler(LoginException)
  25. async def login_exception_handler(_: Request, exc: LoginException):
  26. return ResponseUtil.failure(msg=exc.message, data=exc.data)
  27. # 自定义模型检验异常
  28. @app.exception_handler(ModelValidatorException)
  29. async def model_validator_exception_handler(
  30. _: Request, exc: ModelValidatorException
  31. ):
  32. logger.warning(exc.message)
  33. return ResponseUtil.failure(msg=exc.message, data=exc.data)
  34. # 自定义字段检验异常
  35. @app.exception_handler(FieldValidationError)
  36. async def field_validation_error_handler(_: Request, exc: FieldValidationError):
  37. logger.warning(exc.message)
  38. return ResponseUtil.failure(msg=exc.message)
  39. # 自定义权限检验异常
  40. @app.exception_handler(PermissionException)
  41. async def permission_exception_handler(_: Request, exc: PermissionException):
  42. return ResponseUtil.forbidden(data=exc.data, msg=exc.message)
  43. # 自定义服务异常
  44. @app.exception_handler(ServiceException)
  45. async def service_exception_handler(_: Request, exc: ServiceException):
  46. logger.error(exc.message)
  47. return ResponseUtil.error(data=exc.data, msg=exc.message)
  48. # 自定义服务警告
  49. @app.exception_handler(ServiceWarning)
  50. async def service_warning_handler(_: Request, exc: ServiceWarning):
  51. logger.warning(exc.message)
  52. return ResponseUtil.failure(msg=exc.message, data=exc.data)
  53. # 处理其他http请求异常
  54. @app.exception_handler(HTTPException)
  55. async def http_exception_handler(_: Request, exc: HTTPException):
  56. return JSONResponse(
  57. content=jsonable_encoder({"code": exc.status_code, "msg": exc.detail}),
  58. status_code=exc.status_code,
  59. )
  60. # 处理其他异常
  61. @app.exception_handler(Exception)
  62. async def exception_handler(_: Request, exc: Exception):
  63. logger.exception(exc)
  64. return ResponseUtil.error(msg=str(exc))