# -*- coding: utf-8 -*- from traceback import format_exc import uvicorn from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError, HTTPException from loguru import logger from starlette.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse from bean.Result import JsonResult from concurrency.http.HttpServiceImpl import HttpServiceImpl from enums.ExceptionEnum import ExceptionType from exception.CustomerException import ServiceException from router import api_router class HttpDispatcherService: __slots__ = () def __init__(self, service_config): app = FastAPI(title="机场媒体服务", description="机场媒体服务API文档", version='1.0.2') app.include_router(api_router) # self.register_middleware(app) HttpServiceImpl(service_config) self.register_exception(app) uvicorn.run(app) @staticmethod def register_middleware(app): origins = [ "http://localhost", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @staticmethod def register_exception(app): @app.exception_handler(RequestValidationError) async def request_validation_exception_handler(request: Request, exc: RequestValidationError): logger.error("参数验证为通过: {}", exc.errors()) return JSONResponse(status_code=400, content=JsonResult.error(msg="参数验证未通过,请检查参数是否正确!")) @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): logger.error("http请求异常: {}", format_exc()) return JSONResponse(status_code=exc.status_code, content=JsonResult.error(msg=str(exc.detail))) @app.exception_handler(ServiceException) async def service_exception_handler(request, exc: ServiceException): logger.error("服务异常: {}", exc.msg) return JSONResponse(status_code=400, content=JsonResult.error(code=exc.code, msg=exc.msg)) @app.exception_handler(Exception) async def exception_handler(request, exc): logger.error("未知异常: {}", format_exc()) return JSONResponse(status_code=500, content=JsonResult.error(msg=ExceptionType.SERVICE_INNER_EXCEPTION.value[1]))