我有一个引用以下代码的 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);
}
}
这是调用的代码 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();
}
这是一个async void
. 避免 async void 方法的主要原因之一是您无法处理它们抛出的异常。
在调用者中使它成为一个async Task
和await
它。
请注意,您随后在该呼叫者中遇到了相同的问题, async void Process(...)
把它做好,然后async Task
按照自己的方式工作。async/await 应该形成一个链,从您的 GUI 或控制器到异步 I/O 调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句