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

11,976

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);
});    
Share:
11,976
Erik
Author by

Erik

Updated on July 13, 2022

Comments

  • Erik
    Erik almost 2 years

    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?

  • Peter Dvukhrechensky
    Peter Dvukhrechensky over 4 years
    The following events should not be emitted: error, connect, disconnect, disconnecting, newListener, removeListener, ping, pong. They're listed at the bottom of this documentation page socket.io/docs/emit-cheatsheet
  • Henadzi Rabkin
    Henadzi Rabkin over 2 years
    @PeterDvukhrechensky Page Not Found ...
  • Peter Dvukhrechensky
    Peter Dvukhrechensky over 2 years
    @GennadiyRyabkin they have restructured their doc section. The URL now depends on the version you use. The page I pointed to in my previous comment was for version 2 and it's now here socket.io/docs/v2/emit-cheatsheet There are two more cheatsheets for version 3 and version 4. socket.io/docs/v3/emit-cheatsheet socket.io/docs/v4/emit-cheatsheet