Sub topic 10
Reporting errors after the response has started
This chapter assumes you can write a FastAPI route, know what an async generator is, and have seen the /chat endpoint from the previous chapters. It covers what happens when generation fails after the first byte has already been sent.
Why the usual error handling does not work
In a normal route, you raise HTTPException and FastAPI sends a 500 or 422 response. That works because nothing has been sent yet.
A streaming response is different. FastAPI sends the status line and headers first, usually 200 OK, and then pulls chunks from your generator. If the model call fails halfway through, the client has already been told the request succeeded. You cannot change the status code, and you cannot send a second response.
What happens next depends on how you handle the exception inside the generator:
- If you let the exception escape, the server closes the connection early. A client sees a truncated body, or a transport error such as "incomplete chunked read". It cannot tell a crash from a network problem.
- If you catch the exception and yield an error message, the client gets a clear signal in the same stream it is already reading.
The second option is the one to use.
Catch the error inside the generator
The token_events generator from the endpoint wraps its work in try and except. The error handling is the part to focus on:
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
trycovers thecreatecall too. The call runs when the generator is first iterated, which is after the headers are sent. A bad API key or a rate limit therefore also arrives as an error event, not as an HTTP error status. - The error event uses the same framing as the token events: an
event:line, adata:line holding JSON, and a blank line. - The message is fixed text,
"generation failed". Provider exceptions can contain request details, so do not sendstr(exc)to the client.
Give the client a clear ending
With this design, every stream ends in one of two ways. A done event means success. An error event means failure. If neither arrives, the connection broke, and the client should treat the output as incomplete.
The client from the previous chapter already handles error events. The key piece is the event name tracking:
if line.startswith("event:"):
event = line[len("event:"):].strip()
elif line.startswith("data:"):
data = json.loads(line[len("data:"):])
if event == "error":
print("\n[error]", data["message"])Common mistakes
- Catching
Exceptionand swallowing it. The client gets an error event, but you get nothing. Log the exception on the server, withlogger.exception(...), before you yield the event. - Catching
BaseException. In asyncio,CancelledErroris raised when the client disconnects. If you catch it and keep yielding, you break cancellation.except Exceptiondoes not catch it in current Python versions, which is why the code uses it. The next chapter covers cancellation in detail. - Validating late. Check things you can check up front, such as prompt length, before you return
StreamingResponse. The Pydantic model does this. A failed validation still returns a normal422, because no stream has started.
Exercise
A client calls /chat, receives three token events, and then the model provider times out. What status code does the client see, and how does it learn about the failure?
Show answer
The client sees 200, because the headers were sent before generation began. It learns about the failure from an event: error message that the generator yields from its except block. If the generator let the exception escape instead, the client would only see a truncated stream.
Exercise
Why is it a mistake to yield str(exc) in the error event, and what should you do instead?
Show answer
Exception text from a provider can include internal details such as request IDs, URLs, or configuration. Send a fixed, generic message to the client, and record the full exception on the server with logger.exception.