[Python] How to catch or process RequestValidationError exceptions differently in a FastAPI...

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    How to correctly combine RequestValidationError exception handlers, such as:

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request, exc):
    response = prepare_response({}, g_ERROR__INCORRECT_PARAMS)

    return JSONResponse(content=response)


    and a middleware function, such as:

    @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):


    while, in all other cases, the following function should be triggered:

    @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 response, and the following:

    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, it doesn't work at all, after the following line of code:

    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, and on the other hand, some exceptions (incorrect parameters, etc.) should be tracked before the intermediate code or inside it, but not deeper.

    Continue reading...

Compartilhe esta Página