This is very straightforward : thereadyState property of the websocket contains the connection of the websocket at all times as specified in the WebSocket API
It will be one of the following values : CONNECTING OPEN CLOSING or CLOSED
A way to work around the error would be something like this :
if (yourWsObject.readyState !== WebSocket.CLOSED) {
// Do your stuff...
}