Websocket handler detect disconnect

I’m new to the Sanic framework and I have a little problem with a websocket handler.
My code looks like that:

import asyncio
import sanic
from websockets.exceptions import ConnectionClosed

@app.exception(ConnectionClosed)
async def hey(req, ex):
    print("print this?")

@app.websocket('/random/<nickname:[A-z]+>')
async def random_ws_handler(request, ws, nickname):
    while True:
        if ws is None:
            print("closed")
            break
        else:
            print("connection is on")
        await asyncio.sleep(0.2)
    print("Handler shutting down")

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8000, debug=True)

As you can see, Under my websocket handler random_ws_handler I run a while loop that prints “connection is on” all the time the connection is still running.
Then I try to print “closed” when the connection is closed by the client and finally - print “Handler shutting down”.

When I run the server and connect with a simple client. the meesage “connection is on” is written to the screen perfectly. But when I close the connection from the client, I don’t see any detection in the server, no “closed” or “Handler is shutting down”. It seems the handler just stop running (I no longer see the “connection is on” message)…
How can I detect when a handler finish his work (like when his websocket connection get closed)?
I tried to use @app.exception(ConnectionClosed) But it does not work… maybe i’m not using it in the right way?

The main reason for me to detect that is to announce to redis pubsub clients that the websocket left(user) and for close the connection itself to the redis server and stuff like that…
Any suggestions?

Thanks!

I can give you a snippet over the weekend when I am at a computer. In the mean time, take a look at this gist that I prepared to handle both websockets and pubsub. It might help push you in the right direction. It has handling for detecting when a connection is closed client side.