How to catch `WebSocket connection to 'ws://xxx:nn' failed: Connection closed before receiving a handshake response` error?
Let's say I have a node server started with port nn
, and there is not any WebSocket service on it.
And the problem is that my client trys to connect a WebSocket service to this server.
Obviously, it should fail to connect to the server.
But I couldn't catch this error, my client code is the following:
try {
this.ws = new WebSocket('ws://xxx:nn');
} catch ( e ) {
fallback();
console.warn(e);
}
My expectation is that the fallback
method gets called while connecting fails, but actually the error is not caught by the above try...catch
Does anyone know how to catch the error in my usecase?
Solution 1:
You can register for onError callback of websocket object
exampleSocket.onerror=function(event){
console.log("Error");
}
You can refer following example. http://jsfiddle.net/g28yuymv/1/
catching error example http://jsfiddle.net/g28yuymv/4/
Solution 2:
Looking at the HTML5 WebSockets spec, you can pass a value into the close() method. Then on the onclose() event listener you can check against that value. This gives you the opportunity to set handlers for different disconnect scenarios and then handle everything else as a generic error.
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#close()
var _websocket;
function wsConnect() {
if (_websocket) {
_websocket.close(3001);
} else {
_websocket = new WebSocket("wss://echo.websocket.org1");
_websocket.onopen = function() {
console.log('connected');
};
_websocket.onmessage = function(msg) {
console.log(msg);
};
_websocket.onclose = function(evt) {
if (evt.code == 3001) {
console.log('ws closed');
_websocket = null;
} else {
_websocket = null;
console.log('ws connection error');
}
};
_websocket.onerror = function(evt) {
if (_websocket.readyState == 1) {
console.log('ws normal error: ' + evt.type);
}
};
}
}
wsConnect();
sweet fiddle: https://jsfiddle.net/lamarant/ry0ty52n/