From 77867b44e626aedfba58cf9729100e3cc1a808a8 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Sat, 22 Oct 2016 22:00:15 +0800 Subject: [PATCH] Use better exception handling Parsing the message of an exception to decide what to do next is a bad practice, because it's easy that the message might be changed by mistake in the future. To enforce the coupling in a stronger way it's better to use exceptions of different type depending on the kind of error, so that we rely on the compiler enforcing the behaviour when doing changes in this error handling areas in the future. This also makes the code a bit more simple and readable. --- TLSharp.Core/Network/MtProtoSender.cs | 15 ++++++++++++--- TLSharp.Core/TelegramClient.cs | 11 ++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index f7c4ef2..2d8babf 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -279,9 +279,7 @@ namespace TLSharp.Core.Network { var resultString = Regex.Match(errorMessage, @"\d+").Value; var dcIdx = int.Parse(resultString); - var exception = new InvalidOperationException($"Your phone number registered to {dcIdx} dc. Please update settings. See https://github.com/sochix/TLSharp#i-get-an-error-migrate_x for details."); - exception.Data.Add("dcId", dcIdx); - throw exception; + throw new MigrationNeededException(dcIdx); } else { @@ -484,4 +482,15 @@ namespace TLSharp.Core.Network return new MemoryStream(new byte[len], 0, len, true, true); } } + + internal class MigrationNeededException : Exception + { + internal int DC { get; private set; } + + internal MigrationNeededException(int dc) + : base ("$Your phone number is registered to a different dc: {dc}. Please migrate.") + { + DC = dc; + } + } } \ No newline at end of file diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index 75d0466..40eefaf 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -110,16 +110,9 @@ namespace TLSharp.Core completed = true; } - catch (InvalidOperationException ex) + catch (MigrationNeededException ex) { - if (ex.Message.StartsWith("Your phone number registered to") && ex.Data["dcId"] != null) - { - await ReconnectToDcAsync((int)ex.Data["dcId"]); - } - else - { - throw; - } + await ReconnectToDcAsync(ex.DC); } }