Socket.IO 允许中间件函数传递错误。
var io = require('socket.io')();
io.use(function(socket, next){
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
Run Code Online (Sandbox Code Playgroud)
客户端可以通过侦听默认的“错误”事件来侦听这些错误。
clientIO.on('error', function(err) {
console.log(err);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让 Socket.IO 中间件发出自定义事件名称而不是“错误”(例如,“authentication_error”)?
从我在代码库中看到的,它看起来不像。错误消息通过触发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 {
...
}
}
Run Code Online (Sandbox Code Playgroud)