1

I am working with Github API via Octokit.net. Now I am writing code that responsible for TwoFactorAuth. When I send request for token, if it is 2FA account, than I must get "TwoFactorRequiredException". I am trying to catch it, but insteand of it I get "AggregateException". But when I look in InnerExceptions of Agg..Exc.. then I have only one, and it is "TwoFactorRequiredException". Here is my code:

try
{
    return client.Authorization.Create(newAuthorization).Result.Token;
}
catch ( Octokit.TwoFactorRequiredException )
{
    _navigationService.NavigateAsync($"{nameof(TwoFactorAuthPage)}", animated: false);
}
//catch ( AggregateException ex )
//{
//    foreach ( var exception in ex.InnerExceptions )
//    {
//        Debug.WriteLine(exception.GetType());
//    }
//}

When it is commented, then I have AggregateExceptions, when it is uncommented, then I have AggExc and inside it I have TwoFactor..Exception.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Yura Babiy
  • 515
  • 7
  • 22

1 Answers1

3

That's because client.Authorization.Create(newAuthorization) returns a Task<T>, where T is your result type. Inside a Task, multiple exceptions can occur, that is why the Task Parallel Library returns an AggregateException capturing all the exceptions.

Instead of synchronously blocking on an async method, you should await on it, which asynchronously waits for it's completion. You gain two things from this. The first is that you don't synchronously block and can free the thread, and the second is that await unwraps the exception for you:

public async Task<Token> CallSomethingAsync()
{
    try
    {
        var result = await client.Authorization.Create(newAuthorization);
        result.Token;
    }
    catch ( Octokit.TwoFactorRequiredException )
    {
        _navigationService.NavigateAsync($"{nameof(TwoFactorAuthPage)}", animated: false);
    }
}

Although I'm not sure what NavigateAsync does, I think you may also want to await on it's completion as well.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Thank you for quick responce. – Yura Babiy Sep 26 '16 at 11:53
  • @ Yuval Itzchakov But if I don't need async execution, could it be just fine to catch Aggregate Ex and in it block check it for contain 2FA ex? – Yura Babiy Sep 26 '16 at 11:56
  • 1
    @юрійбабій You could catch the `AggregateException` and iterate it's internal exceptions. Note that synchronously blocking on an async method [can lead to deadlocks](http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html), so you should be careful with that. – Yuval Itzchakov Sep 26 '16 at 11:59