How to catch `WebSocket connection to 'ws://xxx:nn' failed: Connection closed before receiving a handshake response` error?
JavascriptWebsocketJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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/
Solution 3 - Javascript
the above answers cannot be correct. You want to treat it as an error. But that message is more of a warning/info that shows when the following happens.
WebSocketTransport.prototype.close = function() {
debug('close');
var ws = this.ws;
this._cleanup();
if (ws) {
ws.close();
}
};
correct should be:
exampleSocket.onclose = async (event) => {
console.error(event);
//do what you want
}
Solution 4 - Javascript
readyState property sets to 1 when connection is successful hence it can be used to determine the connection state , socket connection usually takes < 1 sec , so we can safely take 3 sec gap and then check the connection state.
Following is the code :
this.ws = new WebSocket('ws://xxx:nn');
setTimeout(() => {
if (this.ws.readyState !== 1) {
alert("Problem connection , kindly contact system admin .");
}
}, 3000);