Reputation: 4125
I'm trying to throw and error server side when my websocket has more than 2 connections. I have this nice client-side onerror
method but I'm unable to reach that part of my code. I'm using nodeJS and the package ws
which has the smallest doc on error handling.
server.js
theWebSocketServer.on('connection', function connection(websocket){
if (theWebSocketServer.clients.length >2) {
// I want to throw the error here and pass it to onerror
console.log('No access allowed', theWebSocketServer.clients.length)
} else {
console.log('happy connection', theWebSocketServer.clients.length)
}
})
client.js
wsConnection.onerror = function(eventInfo) {
alert("There was a connection error!");
console.log("Socket error!", eventInfo);
}
How can I send an error to be handled on the client side JS?
Upvotes: 2
Views: 3333
Reputation: 113365
In the docs, I can't find any way to send an error to the client. Since ws
is a smallish module for websockets, I think it can be used to send messages between server and client and if you need fancy stuff you need to implement your own protocol (the way how you interpret those messages).
For example, in this case it could be something like this:
Client
wsConnection.onmessage = (m) => {
// You can define errors by checking if the event data contains
// something specific: such as the message starts with "Error"
// or if the property of the object is "error" and so on.
if (m.data.startsWith("Error")) {
alert(m.data)
// This will show in the popup:
// "Error: No access allowed"
} else {
// do something else
}
};
wsConnection.onerror = function(eventInfo) {
/* Handle socket errors – e.g. internet goes down, connection is broken etc. */
}
Server:
theWebSocketServer.on('connection', function connection(websocket){
if (theWebSocketServer.clients.length >2) {
websocket.send("Error: No access allowed", err => {
// Ensure your data was actually sent successfully and then
// Close the connection
websocket.close()
// Just in case your data was not sent because
// of an error, you may be interested so see what happened
if (err) { return console.error(err); }
})
// I want to throw the error here and pass it to onerror
console.log('No access allowed', theWebSocketServer.clients.length)
} else {
console.log('happy connection', theWebSocketServer.clients.length)
}
})
Upvotes: 2