[Python] Catch HTTPException raised in route

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    Need to catch HTTPException raised in route in middleware.

    Raise exception in route:

    @worker.get("/v1/error_400")
    async def error_400():
    raise HTTPException(
    status_code=400,
    detail=["400", "error", "message"]
    )


    Then try to catch in middleware:

    async def http_global_exception_middleware(request: Request, call_next: Callable) -> Response:
    try:
    response = await call_next(request)
    return response
    except HTTPException as e:
    raise e
    except Exception as e:
    logger.critical(e)
    raise HTTPException(
    status_code=500,
    detail=str(e)
    )


    In this case try block never catches HTTPException, but if I raised other exception, it caught in last block (except Exception).

    Why can't I catch HTTPException?

    Add middleware in app.py:

    app = FastAPI()

    app.include_router(v1.default.worker)
    app.middleware("http")(http_global_exception_middleware)

    Continue reading...

Compartilhe esta Página