node.jssocketssocket.iosocket.io-1.0

SocketIo.use(function(socket, next)) - Where goes next, how to catch or receive it?


I found example of using socket.IO 1.* width Express 4. Here is a link

Everyting works perfectly. But there is a code:

io.use(function(socket, next) {
try {
    var data = socket.handshake || socket.request;
    if (! data.headers.cookie) {
        return next(new Error('Missing cookie headers'));
    }
    console.log('cookie header ( %s )', JSON.stringify(data.headers.cookie));
    var cookies = cookie.parse(data.headers.cookie);
    console.log('cookies parsed ( %s )', JSON.stringify(cookies));
    if (! cookies[COOKIE_NAME]) {
        return next(new Error('Missing cookie ' + COOKIE_NAME));
    }
    var sid = cookieParser.signedCookie(cookies[COOKIE_NAME], COOKIE_SECRET);
    if (! sid) {
        return next(new Error('Cookie signature is not valid'));
    }
    console.log('session ID ( %s )', sid);
    data.sid = sid;
    sessionStore.get(sid, function(err, session) {
        if (err) return next(err);
        if (! session) return next(new Error('session not found'));
        data.session = session;
        next();
    });
} catch (err) {
    console.error(err.stack);
    next(new Error('Internal server error'));
}
});

So if there is an error, it passes to next. But where goes this next? How to handle this error without try, catch. I mean handle where this next is receiving like in express:

// something here
// And this is callback function which accepts next with err
functin(err, anythingHere){
   if err
      throw err;
   else
      // some code here
}

Solution

  • It goes to the client.

    https://socket.io/docs/server-api/#socket-use-fn

    Errors passed to middleware callbacks are sent as special error packets to clients.

    io.on('connection', (socket) => {
      socket.use((packet, next) => {
        if (packet.doge === true) return next();
        next(new Error('Not a doge error'));
      });
    });
    

    Note that any middlewares following it aren't invoked.

    On the client-side you can handle then like so:

    socket.on('error', function(err){
        // do something with err
    });