You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.5KB

  1. # -*- coding: utf-8 -*-
  2. from traceback import format_exc
  3. import uvicorn
  4. from fastapi import FastAPI, Request
  5. from fastapi.exceptions import RequestValidationError, HTTPException
  6. from loguru import logger
  7. from starlette.middleware.cors import CORSMiddleware
  8. from starlette.responses import JSONResponse
  9. from bean.Result import JsonResult
  10. from concurrency.http.HttpServiceImpl import HttpServiceImpl
  11. from enums.ExceptionEnum import ExceptionType
  12. from exception.CustomerException import ServiceException
  13. from router import api_router
  14. class HttpDispatcherService:
  15. __slots__ = ()
  16. def __init__(self, service_config):
  17. app = FastAPI(title="机场媒体服务", description="机场媒体服务API文档", version='1.0.2')
  18. app.include_router(api_router)
  19. # self.register_middleware(app)
  20. HttpServiceImpl(service_config)
  21. self.register_exception(app)
  22. uvicorn.run(app)
  23. @staticmethod
  24. def register_middleware(app):
  25. origins = [
  26. "http://localhost",
  27. ]
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=origins,
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. @staticmethod
  36. def register_exception(app):
  37. @app.exception_handler(RequestValidationError)
  38. async def request_validation_exception_handler(request: Request, exc: RequestValidationError):
  39. logger.error("参数验证为通过: {}", exc.errors())
  40. return JSONResponse(status_code=400, content=JsonResult.error(msg="参数验证未通过,请检查参数是否正确!"))
  41. @app.exception_handler(HTTPException)
  42. async def http_exception_handler(request, exc):
  43. logger.error("http请求异常: {}", format_exc())
  44. return JSONResponse(status_code=exc.status_code, content=JsonResult.error(msg=str(exc.detail)))
  45. @app.exception_handler(ServiceException)
  46. async def service_exception_handler(request, exc: ServiceException):
  47. logger.error("服务异常: {}", exc.msg)
  48. return JSONResponse(status_code=400, content=JsonResult.error(code=exc.code, msg=exc.msg))
  49. @app.exception_handler(Exception)
  50. async def exception_handler(request, exc):
  51. logger.error("未知异常: {}", format_exc())
  52. return JSONResponse(status_code=500,
  53. content=JsonResult.error(msg=ExceptionType.SERVICE_INNER_EXCEPTION.value[1]))