How to correctly combine RequestValidationError
exception handling functions:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
response = prepare_response({}, g_ERROR__INCORRECT_PARAMS)
return JSONResponse(content=response)
and the middleware code function:
@app.middleware("http")
async def response_middleware(request: Request, call_next):
try:
result = await call_next(request)
res_body = b''
async for chunk in result.body_iterator:
res_body += chunk
response = prepare_response(res_body.decode(), g_ERROR__ALL_OK)
except Exception as e:
response = prepare_response({}, g_ERROR__UNKNOWN_ERROR)
return JSONResponse(content=response)
It is necessary that ONLY the RequestValidationError
exception triggers the following function:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
and all other cases this function:
@app.middleware("http")
async def response_middleware(request: Request, call_next):
Now the response_middleware
function fires all the time and processes the result of validation_exception_handler
, which violates the basic intent of the function.
When using @app.middleware("http")
any exceptions disappear and even without @app.exception_handler(RequestValidationError)
the code consistently generates 200 OK
and
try:
result = await call_next(request)
res_body = b''
async for chunk in result.body_iterator:
res_body += chunk
response = prepare_response(res_body.decode(), g_ERROR__ALL_OK)
except RequestValidationError as e:
response = prepare_response({}, g_ERROR__INCORRECT_PARAMS)
except Exception as e:
response = prepare_response({}, g_ERROR__UNKNOWN_ERROR)
also doesn't work at all after
result = await call_next(request)
no exceptions are thrown
How can this problem be solved?
On the one hand we need middleware code for different functions, on the other hand some exceptions (incorrect parameters, etc.) should be tracked before the intermediate code or inside it, but not deeper.
You should re-raise
RequestValidationError
exception in your middleware.Try changing your middleware code as shown below: