Socket.IO allows middleware functions to pass errors.
var io = require('socket.io')();
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
The client can listen for these errors by listening for the default 'error' event.
clientIO.on('error', function(err) {
console.log(err);
}
Is there any way to have Socket.IO middleware emit custom event names instead of 'error' (e.g., 'authentication_error')?
From what I've seen in the code base, it doesn't look like it. Error messages are sent through a special packet type that triggers the error
event in the client, so it's not a regular message in that respect (that you could replace with another type).
You do have the option to pass along data with the error, though:
// server
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
let err = new Error('Authentication error');
err.data = { type : 'authentication_error' };
next(err);
});
// client
clientIO.on('error', function(err) {
if (err.type === 'authentication_error') {
...
} else {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With