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.
This commit is contained in:
Andres G. Aragoneses 2016-10-22 22:00:15 +08:00
parent bbc6308a54
commit 77867b44e6
2 changed files with 14 additions and 12 deletions

View file

@ -279,9 +279,7 @@ namespace TLSharp.Core.Network
{ {
var resultString = Regex.Match(errorMessage, @"\d+").Value; var resultString = Regex.Match(errorMessage, @"\d+").Value;
var dcIdx = int.Parse(resultString); 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."); throw new MigrationNeededException(dcIdx);
exception.Data.Add("dcId", dcIdx);
throw exception;
} }
else else
{ {
@ -484,4 +482,15 @@ namespace TLSharp.Core.Network
return new MemoryStream(new byte[len], 0, len, true, true); 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;
}
}
} }

View file

@ -110,16 +110,9 @@ namespace TLSharp.Core
completed = true; completed = true;
} }
catch (InvalidOperationException ex) catch (MigrationNeededException ex)
{ {
if (ex.Message.StartsWith("Your phone number registered to") && ex.Data["dcId"] != null) await ReconnectToDcAsync(ex.DC);
{
await ReconnectToDcAsync((int)ex.Data["dcId"]);
}
else
{
throw;
}
} }
} }