TsgcWebSocketClient | Client Exceptions

Sometimes there are errors in communications: the server can disconnect a connection because it is not authorized or a message does not have the correct format. There are 2 events where errors are captured.

OnError

This event is fired every time there is an error in WebSocket protocol, like invalid message type, invalid utf8 string...

OnError is also fired with Connection = nil when WriteData, WriteAndWaitData or Ping cannot send a message because the client is not connected, or, for WriteData and WriteAndWaitData, because the WebSocket handshake has not completed yet. The Error parameter is then Data not sent, the client is not connected or its handshake has not completed. No exception is raised to the caller and the client is not disconnected, so always check Connection for nil before using it in this event.


procedure OnError(Connection: TsgcWSConnection; const Error: string);
begin
  WriteLn('#error: ' + Error);
end;

 

OnException

This event is fired every time there is an exception, such as writing to a socket that is not active or accessing an object that does not exist.

 


procedure OnException(Connection: TsgcWSConnection; E: Exception);
begin
  WriteLn('#exception: ' + E.Message);
end;

By default, when a connection is closed by the server, an exception will be fired. If you do not want these exceptions to be fired, disable Options.RaiseDisconnectExceptions.

Options.RaiseDisconnectExceptions also controls the OnError report of messages that could not be sent because the client is not connected. Set it to False to drop those messages silently, as earlier versions did.