from fastapi import FastAPI, status from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError, ResponseValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from loguru import logger from starlette import requests from starlette.middleware.errors import ServerErrorMiddleware from starlette.requests import Request from starlette.types import ASGIApp from app.api import api_router app = FastAPI() # fix cors error when 500 occurs according to https://github.com/tiangolo/fastapi/issues/4071#issuecomment-950833326 def global_execution_handler(request: requests.Request, exc: Exception) -> ASGIApp: logger.exception(exc) return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content=f"Unknown Error: {exc.args[0]}", ) app.add_middleware( ServerErrorMiddleware, handler=global_execution_handler, ) origins = [ '*' ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(api_router, prefix="") @app.exception_handler(RequestValidationError) def validation_exception_handler(request: Request, exc: RequestValidationError): logger.exception(exc) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}), ) @app.exception_handler(ResponseValidationError) def validation_exception_handler(request: Request, exc: ResponseValidationError): logger.exception(exc) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}), )