如何发出错误可能在客户端的错误处理程序中捕获

如何发出错误可能在客户端的错误处理程序中捕获

本文介绍了如何发出错误可能在客户端的错误处理程序中捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在连接处理程序中发出错误,并在客户端捕获此类错误:

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

//server-side.js

// 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'));
});

//清洁侧

var socket = io.connect(window.location.origin);
socket.on('error', fucntion () {
   console.log('never happend');
});

但是问题是socket.emit('error', new Error('Some error happend'));在服务器端总是抛出错误并使Node.js服务器崩溃,原因是此问题

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?

推荐答案

服务器

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

客户端

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

不幸的是,

error是保留名称.

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);
});

这篇关于如何发出错误可能在客户端的错误处理程序中捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:44