Socket.IO - Error Handling

We have worked on local servers until now, which will almost never give us errors related to connections, timeouts, etc. However, in real life production environments, handling such errors are of utmost importance. Therefore, we will now discuss how we can handle connection errors on the client side.

The client API provides us with following built in events −

  • Connect − When the client successfully connects.

  • Connecting − When the client is in the process of connecting.

  • Disconnect − When the client is disconnected.

  • Connect_failed − When the connection to the server fails.

  • Error − An error event is sent from the server.

  • Message − When the server sends a message using the send function.

  • Reconnect − When reconnection to the server is successful.

  • Reconnecting − When the client is in the process of connecting.

  • Reconnect_failed − When the reconnection attempt fails.

To handle errors, we can handle these events using the out-socket object that we created on our client.

For example – If we have a connection that fails, we can use the following code to connect to the server again −

socket.on('connect_failed', function() {
   document.write("Sorry, there seems to be an issue with the connection!");