自定义Socket.IO中间件错误事件?

时间:2016-06-29 19:28:22

标签: node.js socket.io

Socket.IO允许中间件函数传递错误。

var io = require('socket.io')();
io.use(function(socket, next){
    if (socket.request.headers.cookie) return next();
    next(new Error('Authentication error'));
});

客户可以通过收听默认错误'来听取这些错误。事件

clientIO.on('error', function(err) {
    console.log(err);
}

有没有办法让Socket.IO中间件发出自定义事件名称而不是'错误' (例如,' authentication_error')?

1 个答案:

答案 0 :(得分:3)

从我在代码库中看到的情况来看,它看起来并不像。错误消息通过触发客户端中error事件的特殊数据包类型发送,因此在这方面它不是常规消息(您可以用其他类型替换)。

您可以选择传递包含错误的数据:

// 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 {
    ...
  }
}