0

My coffee code to establish websocket connection when it isn't present return an error:

socket = new WebSocket('ws://localhost:8080')
#=> Firefox can't establish a connection to the server at ws://localhost:8080/.
#=> socket = new WebSocket('ws://localhost:8080');

It's normal behaviour of WebSocket, but I want WebSockets work like this:

# pseudocode
if websocket.establish_connection()
  # do thing #1
else
  do thing no.2

I think about try...catch but I think it's dirty. Is there any other way of troubleshooting?

Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
  • there is some `readyState` property, maybe this helps http://stackoverflow.com/questions/11809267/how-do-i-know-if-connection-is-alive-with-websockets – john Smith May 06 '15 at 16:10

1 Answers1

1

Its not actually throwing an Error, the program execution continues. Its simply logging the error (asynchronously) to the console. To handle connection failures, you can bind to the sockets onerror event.

Something like this could work:

function establishWSConnection(url) {
    return new Promise(function(res, rej) {
        var ws = new WebSocket(url);
        ws.onerror = rej;
        ws.onopen = function () {
            ws.onerror = null;
            res(ws);
        }
    });
}

establishWSConnection('ws://localhost:1234').then(function(ws) {
    // do stuff
}).catch(function(err){
    console.log(err);
});
levi
  • 23,693
  • 18
  • 59
  • 73