Skip to content
TheChatArchiveThe Chat Archive
o4-mini-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

fastapi how to output to console 422 error with corresponding message whats wrong

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-opus-4-20250514-thinking-16k’s answer.
  1. User

    fastapi how to output to console 422 error with corresponding message whats wrong

  2. Assistant

    Here’s a minimal example showing two ways to catch all 422/validation errors and log them (to your console or any configured logger) with their Pydantic‐style messages:

    1. Using a custom exception‐handler for FastAPI’s RequestValidationError
    2. Using a middleware to catch any HTTP response with status code 422

    —–

    1) Exception‐handler for RequestValidationError

    from fastapi import FastAPI, Request
    from fastapi.exceptions import RequestValidationError
    from fastapi.responses import JSONResponse
    import logging
    
    # 1) Configure root logger to print to console
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s"
    )
    logger = logging.getLogger("uvicorn.error")  # or your own logger
    
    app = FastAPI()
    
    
    # 2) Catch Pydantic validation errors (422) before they bubble up
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        # Log the detailed errors:
        for err in exc.errors():
            loc = " -> ".join(str(x) for x in err["loc"])
            msg = err["msg"]
            typ = err["type"]
            logger.error(f"ValidationError at {loc}: {msg} ({typ})")
    
        # Return the standard 422 response (you can customize this too)
        return JSONResponse(
            status_code=422,
            content={"detail": exc.errors()},
        )
    
    
    # 3) A sample endpoint expecting an int in the body
    @app.post("/items/")
    async def create_item(q: int):
        return {"q": q}
    

    Now if you call:

    curl -X POST "http://localhost:8000/items/" -H "Content-Type: application/json" -d '{"q":"not-an-int"}'
    

    Your console will show:

    2023-10-08 12:34:56 ERROR ValidationError at body -> q: value is not a valid integer (type_error.integer)
    

    And the HTTP response remains the normal 422 with the JSON detail array.

    —–

    2) Middleware approach (catching any 422 “slipped through”)

    If you want to log every outgoing 422 response (whether from validation or an explicit HTTPException(status_code=422)):

    from fastapi import FastAPI, Request
    from starlette.types import Message
    import logging
    
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("uvicorn.error")
    
    app = FastAPI()
    
    @app.middleware("http")
    async def log_422_middleware(request: Request, call_next):
        response = await call_next(request)
    
        if response.status_code == 422:
            # starlette.responses.Response.body() is async
            body_bytes = b"".join([chunk async for chunk in response.body_iterator])
            body = body_bytes.decode(errors="ignore")
            logger.error(f"422 response for {request.method} {request.url.path}: {body}")
            # restore the original body iterator for FastAPI to send it back:
            async def fake_stream(send: Message):
                await send({"type": "http.response.body", "body": body_bytes, "more_body": False})
            response.body_iterator = fake_stream
    
        return response
    
    @app.post("/items/")
    async def create_item(q: int):
        return {"q": q}
    

    With this middleware in place, any 422 coming out of your app will be logged along with its response payload.

    —–
    Pick the approach that suits you best:

    • Exception‐handler if you specifically care about Pydantic/validation errors.
    • Middleware if you want a blanket “log all 422s” solution.
  3. User

    output it in one line

  4. Assistant

    Here’s a quick tweak so that all 422 validation errors print as a single console line:

    import json
    import logging
    from fastapi import FastAPI, Request
    from fastapi.exceptions import RequestValidationError
    from fastapi.responses import JSONResponse
    
    # — configure logging once
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    logger = logging.getLogger("uvicorn.error")
    
    app = FastAPI()
    
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        # 1) flatten every error into "loc: msg"
        single_line = " | ".join(
            f"{'.'.join(str(x) for x in err['loc'])}: {err['msg']}"
            for err in exc.errors()
        )
        # 2) include method & path if you like
        logger.error(f"422 {request.method} {request.url.path} → {single_line}")
    
        # 3) return the normal 422 response
        return JSONResponse(status_code=422, content={"detail": exc.errors()})
    
    @app.post("/items/")
    async def create_item(q: int):
        return {"q": q}
    

    Now a bad request like:

    POST /items/   {"q":"foo"}
    

    Logs something like:

    422 POST /items → body: q: value is not a valid integer
    

    — If you’d rather dump the raw errors() array as compact JSON, swap step 1 with:

    single_line = json.dumps(exc.errors(), separators=(",", ":"))
    logger.error(f"422 → {single_line}")
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.