我有一个引用以下代码的Windows服务.使用下面的方法,我的代码包含一个try..catch块,但它似乎并没有catch RefereshTokenException认为是thrown在下面的方法.显然我的理解async是不正确的.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是调用的代码 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();
}
Run Code Online (Sandbox Code Playgroud)
这是一个async void.避免异步void方法的一个主要原因是您无法处理它们抛出的异常.
使它成为一个async Task和await它在呼叫者.
请注意,您在该调用者中遇到相同的问题, async void Process(...)
让它成为一个async Task好的并且一路向上.async/await应该形成一个链,从GUI或Controller到异步I/O调用.