Bytechie
Bytechie

Reputation: 45

Socket.io emit empty object if it's an Error

When I emit an object of the Error class this one arrives empty on the client-side. How can I send an Error object through socket.io ??

Example:

let error = new Error("test");
client.emit(road, { success: false, err: error });

result in:

websocket google chrome

About the server (that emit the Error):

About the client (that receive the Error):

Upvotes: 1

Views: 792

Answers (1)

Mathias Osterhagen
Mathias Osterhagen

Reputation: 424

As writing here: https://stackoverflow.com/a/20916142/12530707 Socket.io perform a JSON.stringify on the object before to send it on the socket. As you can figure out by yourself in your console, typing JSON.stringify(new Error("test")) result in {};

What I can advise you is to check the object class instance before to send it in order to convert it in a "valid" object yourself:

if (err instanceof Error)
   err = { message: err.message, stack: err.stack };
client.emit(road, { success: false, err: err });

Upvotes: 3

Related Questions