Skip to content

StreamingResponse generater throws exception, how to catch it and return 400? #10138

Closed Answered by Kludex
Cameronsplaze asked this question in Questions
Discussion options

You must be logged in to vote

The above code example as is will throw a 500 ValueError: This is an error.

No, the code above doesn't throw a 500. It throws a 200.

This may be a bit confusing, but response headers, and status code are sent in the beginning (before processing the stream).

You may benefit from something called HTTP trailers, which are supported by uvicorn. You can see more background about it on: encode/starlette#1876 (tentative PR against Starlette, that I didn't go through).

Well, to summarize... No way to catch errors and send a different error code using the Response classes from Starlette. You can create your custom one and only send the http.response.start AFTER processing the body (which is also…

Replies: 6 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@rossgray
Comment options

@sandangel
Comment options

@Smacl3r
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@SidJain1412
Comment options

Answer selected by Kludex
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
9 participants