如何将错误对象传递给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的标准序列化执行其操作(这将导致错误
实例的纯空对象。
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屋!