Sub topic 10
Reporting errors after the response has started
This chapter assumes you have read the earlier chapters of this tutorial. You should know how an async generator feeds StreamingResponse, how Server-Sent Events (SSE) frame messages, and how the /chat endpoint streams chunks from an AsyncOpenAI client. You should also be comfortable with Python try/except and basic logging.
Why a streamed response cannot report errors normally
An HTTP response starts with a status line and headers. The body follows. In a normal endpoint, FastAPI runs your code, sees an exception, and sends 500 Internal Server Error. Nothing has been sent yet, so it can still choose the status.
A streaming response reverses that order. Starlette sends the status line and headers as soon as it starts the response. For StreamingResponse that is 200 OK plus Content-Type: text/event-stream, before your generator has produced a single chunk, so the generator's first error can already be too late to change the status. After that point the status is committed. If the LLM provider times out on token 40, you cannot go back and send a 502. The client has already seen 200.
So an error that occurs during streaming needs a different channel. You have two options:
- Send the error inside the stream, as an SSE event the client knows how to read.
- Let the connection break and rely on the client to notice.
The first option is almost always better, because the client can tell the user what happened and does not have to guess.
What the client sees in each case
| When the failure happens | What the server can send | What the client sees |
|---|---|---|
| Before the response object is returned (validation, bad API key, rate limit on connect) | A real error status such as 422 or 502 | A non-200 status |
| After the response starts, and your code catches it | An `error` SSE event, then end of stream | Status 200, then an `error` event |
| After the response starts, and nothing catches it | Nothing more. The server logs the exception and closes the connection | Status 200, then a truncated body, often an "incomplete read" error from the HTTP library |
| The client disconnects | Nothing. The generator is cancelled | Not applicable |
The third row is the one to avoid. The client cannot distinguish a crashed server from a network drop.
Catch inside the generator
The /chat endpoint from the previous chapter already follows this rule. Its generator wraps all the work in try and yields an error event from the except branch:
async def token_events(client: AsyncOpenAI, prompt: str):
try:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except Exception:
yield sse("error", {"message": "generation failed"})Three details matter here.
- The
exceptyields instead of raising. Anerrorevent is a normal part of the protocol, and the response then ends cleanly. - The message is generic. Exception text from a provider can contain request IDs, account details, or parts of your prompt. Send the client a short, stable message. Keep the detail in your logs.
except Exceptiondoes not catch cancellation. In current Python,asyncio.CancelledErrorderives fromBaseException, so this handler lets it through. That is what you want, and the next chapter relies on it. Do not widen the handler toexcept BaseException, or the generator will swallow the cancellation that signals a client disconnect.
Log the real exception
The generic client message is only useful if you can still find the cause. Add logging in the handler:
import logging
logger = logging.getLogger(__name__)
# inside the generator
except Exception:
logger.exception("LLM stream failed")
yield sse("error", {"message": "generation failed"})logger.exception records the full traceback at ERROR level. Without it, your error events would be invisible on the server side.
Fail early with a real status code when you can
The try block above also covers the call that opens the stream. If the API key is wrong or the provider rejects the request, that failure is reported as an in-stream error event with status 200. Monitoring tools that count 5xx responses will miss it.
With the OpenAI client, create(..., stream=True) raises as soon as the provider rejects the request. It only returns the stream object once the provider has accepted it. You can therefore open the stream in the endpoint function, before creating the StreamingResponse. If opening fails, FastAPI is still in the normal phase and can send a proper status. Only the iteration over chunks stays inside the generator.
import json
import logging
import os
from functools import lru_cache
import openai
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
app = FastAPI()
logger = logging.getLogger(__name__)
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI()
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def token_events(stream):
try:
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except Exception:
logger.exception("LLM stream failed mid-stream")
yield sse("error", {"message": "generation failed"})
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
try:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": body.prompt}],
stream=True,
)
except openai.APIError:
logger.exception("LLM request failed before streaming")
raise HTTPException(status_code=502, detail="LLM unavailable")
return StreamingResponse(
token_events(stream),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)The two phases now have separate error handling:
- Failures before the first chunk become a
502that load balancers, dashboards, and client retry logic already understand. - Failures after that become an
errorevent.
The trade-off is that the endpoint waits for the provider to accept the request before it replies. That wait is short, and it is the time you would be waiting anyway.
Make the client treat the stream as a state machine
Server-side handling only works if the client reads it. A client has three possible outcomes for a stream:
- It received
done, so the answer is complete. - It received
error, so the answer is partial and the server knows it. - The stream ended with neither, so the connection was cut and the answer may be truncated.
The third case is easy to miss. Extend the reader from the earlier chapter to return which outcome occurred:
import asyncio
import json
import httpx
async def read_chat(prompt: str) -> str:
outcome = "dropped"
try:
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream(
"POST", "http://localhost:8000/chat", json={"prompt": prompt}
) as resp:
resp.raise_for_status()
event = None
async for line in resp.aiter_lines():
if line.startswith("event:"):
event = line[len("event:"):].strip()
elif line.startswith("data:"):
data = json.loads(line[len("data:"):])
if event == "token":
print(data["text"], end="", flush=True)
elif event == "done":
outcome = "done"
elif event == "error":
outcome = "error"
print("\n[error]", data["message"])
except httpx.RemoteProtocolError:
outcome = "dropped"
print()
return outcome
print(asyncio.run(read_chat("Say hello")))raise_for_status() handles the early 502 case. The event checks handle the in-stream case. The RemoteProtocolError handler and the default "dropped" value handle a connection that ended without a terminal event. Whatever the UI does on error should also happen on dropped, for example showing a retry button next to the partial text.
Test the error path
The fake-client approach from the testing chapter works for failures too. Make the fake stream yield one chunk and then raise:
from types import SimpleNamespace as NS
from fastapi.testclient import TestClient
from main import app, get_client
class FailingClient:
class chat:
class completions:
@staticmethod
async def create(**kwargs):
async def gen():
yield NS(choices=[NS(delta=NS(content="Hel"))])
raise RuntimeError("provider dropped the connection")
return gen()
def test_chat_reports_midstream_error():
app.dependency_overrides[get_client] = lambda: FailingClient()
try:
with TestClient(app) as client:
with client.stream("POST", "/chat", json={"prompt": "hi"}) as resp:
status = resp.status_code
body = "".join(resp.iter_text())
finally:
app.dependency_overrides.clear()
assert status == 200
assert "event: token" in body
assert "event: error" in body
assert "event: done" not in bodyThe test asserts the status is 200, which pins down the behavior this chapter describes: the status does not change after streaming starts.
Common mistakes
- Raising
HTTPExceptioninside the generator. By then the status is sent, so the exception cannot change it. It only produces a server-side traceback and a broken stream. - Sending
str(exc)to the client. This leaks internal detail. Use a fixed message, or a short error code the client can map to text. - Emitting
doneunconditionally. Put it after the loop inside thetry, as the endpoint does. If it sat in afinallyblock, a failed stream would also reportdone. - Catching
BaseException. This swallows cancellation, so work continues after the client has gone.
Exercise
A stream has already sent three token events when the provider raises an exception. Why can't the endpoint return a 502 at that point, and what should the generator do instead?
Show answer
The status line and headers (200 OK) were sent when the response started, and HTTP has no way to change them afterwards. The generator should catch the exception, log it with logger.exception, yield an error SSE event with a generic message, and then end. The client treats the missing done event plus the error event as a failed, partial answer.
Exercise
Why does the endpoint in this chapter open the stream before it creates the StreamingResponse, and what is the cost?
Show answer
Opening the stream first means failures such as an invalid API key or a rejected request are raised while FastAPI can still send a real status, so the client gets a 502 and monitoring sees a 5xx. The cost is that the endpoint waits for the provider to accept the request before it responds, which is a short delay that the stream would have had anyway.