How to emit error to be possible catch it on error handler on client-side?

Erik picture Erik · Nov 23, 2015 · Viewed 9.4k times · Source

I need to emit error in my connection handler and catch it on client-side something like this:

// server-side

var http = require('http');
var sio = require('socket.io');
var app = require('express')();

var server = require('http').createServer(app).listen(3000, function () {
    console.log('Server listening on 3000 port');
});

var io = sio.listen(server);

io.on('connection', function (socket) {
    // Do something and emit error...
    socket.emit('error', new Error('Some error happened'));
});

// client-side

var socket = io.connect(window.location.origin);
socket.on('error', function () {
   console.log('Never happens...');
});

But the problem is socket.emit('error', new Error('Some error happend')); on server-side always throws error and crashes nodejs server due this issue

Could you help how to emit error and handle on client side properly?

Answer

kaytrance picture kaytrance · Nov 23, 2015

server

socket.emit('my error', 'Some error happened');

client

socket.on('my error', function (text) {
   console.log(text);
});

error is a reserved name, unfortunately.

If you need to catch it on client side, use some other event name to notify client

// server
socket.on("error", function() {
    socket.emit("my error", "Something bad happened!");
});

// client
socket.on('my error', function (text) {
   console.log(text);
});