Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 242
Erik Avatar asked Nov 23 '15 13:11

Erik


Video Answer


1 Answers

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);
});    
like image 132
kaytrance Avatar answered Sep 20 '22 01:09

kaytrance