Handling errors during async StreamingHttpResponse

In an async view, I return a StreamingHttpResponse that uses an async iterator as streaming_content. The iterator fetches its data from another HTTP service. When the other service fails I throw an Exception inside the iterator, but the response (and the iterator) then “hangs” and the connection will not be closed. What is a good way to handle such errors, especially when using async iterators? As the streaming response has already started, I guess it is also not possible anymore to send a 5xx status back to the client, to let it know that something went wrong. How can I inform the client about the error?

Hi @medihack.

Similar to the Handling disconnects example you need to make sure you catch any errors exit the iterator cleanly here. (Exactly how you do that will depend on your code, but ultimately you want the iterator to stop sending more chunks.) The request handler will close the response once the iterator is exhausted. (So using a generator just fall through to the end of the function.)

Yep. Status code was already sent.

I guess you could send a particular last chunk that the client could look out for.

Hi Carlton,

Thanks for your answer! From my research, a streaming response really seems like a disadvantage, especially if you don’t control both the server and the client. Another option to add additional information is to use a Trailer, but you also need to control the client.