I have declared router in coupe with middleware and added the generic handler for any exception that may happen inside addressing calls to some abstract endpoints:
app = fastapi.FastAPI(openapi_url='/api/v1/openapi.json')
app.include_router(v1.api_router, prefix='/api/v1')
app.add_middleware(middlewares.ClientIPMiddleware)
@app.exception_handler(starlette.exceptions.HTTPException)
async def on_request_exception_handler(
request: fastapi.Request,
exc: starlette.exceptions.HTTPException,
):
return fastapi.responses.JSONResponse(
status_code=exc.status_code,
content={
'detail': exc.detail,
'status': exc.status,
},
)
class ClientIPMiddleware(starlette.middleware.base.BaseHTTPMiddleware):
async def dispatch(self, request: fastapi.Request, call_next: typing.Callable):
request.state.client_ip = get_client_ip(request.headers)
return await call_next(request)
In ClientIPMiddleware
class I have to refactor and add something like:
try:
response = await call_next(request)
if request.method != 'GET':
if response.status_code == 200:
return fastapi.responses.JSONResponse(
status_code=200,
content={'status': 'ok'},
)
return response
except Exception as e:
pass
I just need both mechanisms here: the one is for catching all the errors possible at the endpoints' level, the two is for getting either serialized response, or JSONResponse
with status_code
and status
message. In the last snippet of the code try/except
block is odd as it can't catch any error there. Is there any better solution to reach the goal? To add a custom or origin decorator to the app
instance?