Core: use better exception types and messages if things go south

One of the problems is related to [1] so if that bug
happens again, now we'll have more info.

[1] https://github.com/nblockchain/TgSharp/issues/22
This commit is contained in:
Andres G. Aragoneses 2020-10-16 21:19:38 +02:00
parent 0dd6d70c60
commit c37ecd4621

View file

@ -18,6 +18,9 @@ namespace TgSharp.Core.Network
public TcpTransport(string address, int port, TcpClientConnectionHandler handler = null) public TcpTransport(string address, int port, TcpClientConnectionHandler handler = null)
{ {
if (String.IsNullOrEmpty (address))
throw new ArgumentNullException (nameof (address));
if (handler == null) if (handler == null)
{ {
var ipAddress = IPAddress.Parse(address); var ipAddress = IPAddress.Parse(address);
@ -54,9 +57,11 @@ namespace TgSharp.Core.Network
public async Task<TcpMessage> Receive(CancellationToken token = default(CancellationToken)) public async Task<TcpMessage> Receive(CancellationToken token = default(CancellationToken))
{ {
var packetLengthBytes = new byte[4]; var packetLengthLength = 4;
if (await stream.ReadAsync(packetLengthBytes, 0, 4, token).ConfigureAwait(false) != 4) var packetLengthBytes = new byte[packetLengthLength];
throw new InvalidOperationException("Couldn't read the packet length"); var bytesRead = await stream.ReadAsync(packetLengthBytes, 0, packetLengthLength, token).ConfigureAwait(false);
if (bytesRead != packetLengthLength)
throw new InvalidOperationException($"Couldn't read the packet length (was {bytesRead}, expected {packetLengthLength})");
int packetLength = BitConverter.ToInt32(packetLengthBytes, 0); int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);
var seqBytes = new byte[4]; var seqBytes = new byte[4];