1

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?

yose93
  • 75
  • 2
  • 8
  • Does the code in the last snippet raise any exceptions? Also `except Exception as e: pass` - best way to shoot yourself in the foot in Python. – NotAName Mar 12 '21 at 06:17
  • The `try/except` block is odd and wasted, all exceptions are caught inside `await call_next(request) as it actually is. – yose93 Mar 12 '21 at 06:36

0 Answers0