Error management on streaming

Hello there,

Here is the nice example from the documentation to stream a response from a database

@app.route("/")
async def index(request):
   async def stream_from_db(response):
        conn = await asyncpg.connect(database='test')
        async with conn.transaction():
            async for record in conn.cursor('SELECT generate_series(0, 10)'):
                await response.write(record[0])

    return stream(stream_from_db)

A more realist example would be something like this

    try:
       async for record in conn.cursor('SELECT generate_series(0, 10)'):
            await response.write(record[0])
    except:
        logger.error('Database error')

But how I’m suppose to handle the error on the HTTP side ?
On my application, I’m used to “early answer” by returning something like

except:
     return text('Database error', status=500)

but this does not work with a stream coroutinePreformatted text

I’m not sure why you would stream from the database like this, you should be formatting a response to send. I’m assuming something on the frontend is consuming this. If you use an event stream “SSE” You could specify a listener for data messages and error messages. When an exception is thrown you could just stream the error message.

There is an example here the custom protocol part isn’t necessary. https://github.com/huge-success/sanic/issues/683