Reputation: 701
I have a windows service that references the following code. My code that uses the below method contains a try..catch
block but it doesn't seem to catch
RefereshTokenException
that is thrown
in the below method. Obviously my understanding of async
is not correct.
private async void RefreshTokens()
{
try
{
var cognito = new CognitoApi();
var response = cognito.TokenRefresh(_refreshToken);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
_idToken = new AwsToken(response.AuthenticationResult.IdToken);
_accessToken = new AwsToken(response.AuthenticationResult.AccessToken);
}
else
{
await _signIn(_credentials.SiteId, _credentials.LocationId, null);
}
}
catch (NotAuthorizedException)
{
await _signIn(_credentials.SiteId, _credentials.LocationId, null);
}
catch (Exception ex)
{
throw new RefreshTokenException("Failed refreshing tokens.", ex);
}
}
This is the code that calls RefreshTokens
public async void Process(QueueMessage queueMessage, Action<QueueMessage> retryAction)
{
_processingCounter.Increment();
try
{
......
IAwsToken idToken = authenticationService.Tokens.IdToken; //This is the code that calls "RefreshTokens" method
........
}
catch (Exception ex)
{
//Code never reaches here...
_logger.Error("Error in ProcessMessage", ex);
}
_processingCounter.Decrement();
}
Upvotes: 0
Views: 108
Reputation: 3037
This is an async void
. One of the main reasons to avoid async void methods is that you cannot handle the exceptions they throw.
Make it an async Task
and await
it in the caller.
Note that you then have the same issue in that caller, async void Process(...)
Make that an async Task
as well and work your way up. async/await should form a chain, from your GUI or Controller down to an async I/O call.
Upvotes: 5