I am working on an app that involves the use of WebSockets. I have the following code as a part of the application:
io.on('connection', socket => {
let PLAYER = {};
// Listener for event 1
// Listener for event 2
// ...
socket.on('setName', ({name, role, room}) => {
PLAYER.name = name;
PLAYER.role = role;
PLAYER.room = room;
try{
joinRoom(PLAYER); // This function can throw an error
socket.emit('roomJoin');
}catch(e){
socket.emit('error', e.message);
return;
}
});
});
Now, when the joinRoom function does throw an error, Node just crashes with the following exception:
events.js:306
throw err; // Unhandled 'error' event
^
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ('error message')
The error event is never emitted. What has made the try catch block fail?
Note: I am using TypeScript, but have removed type declarations in the above snippet as they shouldn't have anything to do with the problem.
Edit 1:
I have recreated the issue with simpler code as follows:
import express from 'express';
import socketio from 'socket.io';
import http from 'http';
const PORT = process.env.PORT || 8000;
const app = express();
const server = http.createServer(app);
const io = socketio(server);
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
const checkLength = (bar) => {
if(bar.length > 14){
throw Error('word is too long!');
}
// ...
}
io.on('connection', socket => {
console.log('new socket connection');
socket.on('foo', ({bar}) => {
try{
checkLength(bar);
}catch(e){
socket.emit('error', e.message);
return;
}
console.log('app did not crash!');
});
}
When the length of bar is greater than 14, the app crashes with the same error mentioned above.