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
}
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
});
Sharing another example for convenience
Node Version : 12.13.1 Express : 4.xx.x Socket IO: 2.1.1 Socket IO client: 2.x.x
io.use((socket, next) => {
if (
process.env.NODE_ENV == "production" &&
socket.handshake.headers.origin != undefined &&
socket.handshake.headers.origin == config.SOCKET_ORIGIN
) {
return next();
} else {
// return next();
return next(new Error("Invalid Origin"));
}
})
.use(async (socket, next) => {
if (socket.handshake.query.token != undefined) {
const verificationResponse = await hlpr.JWTVerification(
socket.handshake.query.token
);
if (verificationResponse.err != null) {
next(new Error("Unauthorized"));
} else {
return next();
}
} else {
next(new Error("Unauthorized"));
}
})
.use(async (socket, next) => {
console.log("***** socket ******");
console.log("***** next ******");
console.log("***** payload Middlewar Check ******");
return next();
})
.on("connection", socket => {
console.log("User Connected Successfully");
});
Client side code
const socket = io.connect('ws://xXx.xXx.x.xXx:xxxx', {
// resource: 'nodejs',
transport: true,
query: {token: "xxxXXXxxXXXXXxxxXXXXxxxxXXXXXXXX"}
});
socket.on('connect', () => {
console.log("*******");
console.log("Successfull Hand Shake");
console.log("*******");
}).on('error', (err) => {
console.log("************ Error ************")
console.log("************ Error ************")
console.log(err)
console.log("************ Error ************")
// Show the toaster with the error
// Try re-connect
// close the socket connection
});
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