Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Socket.IO middleware error events?

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')?

like image 429
user2901933 Avatar asked Jun 29 '16 19:06

user2901933


1 Answers

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 {
    ...
  }
}
like image 160
robertklep Avatar answered Oct 18 '22 14:10

robertklep