如何将错误对象传递给 socket.io 回调 [英] How to pass error object to socket.io callback
问题描述
我在 socket.io 中使用回调
I am using callbacks with socket.io
客户端代码:
socket.emit('someEvent', {data:1}, function(err, result) {
console.log(err.message);
});
服务器代码:
socket.on('someEvent', function(data, callback) {
callback(new Error('testing error'));
});
使用上面的代码,客户端总是打印出undefined
.如果我将服务器端代码更改为以下代码,我可以看到错误消息.
With the above code the client side always prints out undefined
. If I change the server side code to the following I can see the error message.
socket.on('someEvent', function(data, callback) {
callback({message:'testing error'});
});
我可以将自己的自定义对象传递给客户端就好了,只是不能传递错误对象.有什么想法吗?
I can pass my own custom objects to the client just fine, just not the error object. Any ideas?
推荐答案
socket.io
数据被序列化为JSON
,只能表示普通对象.您需要将任何错误序列化为可识别的纯对象格式,或者让 Socket.IO 的标准序列化来完成它的工作(这将导致 Error
实例的纯空对象.
socket.io
data is serialized as JSON
, which can only represent plain objects. You will need to serialize any errors into a recognizable plain-object format, or let Socket.IO's standard serialization do its thing (which will result in a plain empty object for Error
instances.
这篇关于如何将错误对象传递给 socket.io 回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!