问题
I need to emit error in my connection handler and catch it on client-side something like this:
// server-side.js
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 happend'));
});
// cleant-side
var socket = io.connect(window.location.origin);
socket.on('error', fucntion () {
console.log('never happend');
});
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?
回答1:
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);
});
来源:https://stackoverflow.com/questions/33872052/how-to-emit-error-to-be-possible-catch-it-on-error-handler-on-client-side