【问题标题】:Trouble catching exception on Azure Service Bus SendAsync method无法在 Azure 服务总线 SendAsync 方法上捕获异常
【发布时间】:2018-06-10 03:13:50
【问题描述】:

我正在尝试使用以下代码来设置故障条件,即没有可用的网络路径,因此代码根本不能发送到服务总线。我知道这一点是因为我在测试时禁用了网络端口。

尽管如此,我仍然对代码的异步特性感到困惑。我不知道在控制台应用程序中,例如我如何附加一些会注销我知道应该生成的异常的东西。

如何查看异常文本?

        public async Task TestQueueExists()
    {    
        _queueClient = new QueueClient(AppSettings.McasServiceBusConnectionString,
            AppSettings.ListServSyncQueueName);
        Logger.Information(
            $"Queue Created to: {_queueClient.QueueName} with RecieveMode: {_queueClient.ReceiveMode}");
        try
        {
            await _queueClient.SendAsync(new Message("Test".ToUtf8Bytes()));       
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

    }

【问题讨论】:

  • AppDomain.CurrentDomain.UnhandledException 并写入日志文件
  • 好的,你能详细说明一下吗?我不熟悉那种获得期望的方式。
  • 尝试捕捉等待的代码应该可以正常工作
  • 我的猜测是程序在这之后立即崩溃了,这就是您没有看到异常的原因。如果您希望程序在发生该异常时崩溃,请改为写入文件
  • 这个是@Steve。日志文件比控制台输出更适合调查。

标签: c# azure azureservicebus


【解决方案1】:

根据您的代码,我假设您使用的是 Azure Service Bus .NET Standard 客户端库 Microsoft.Azure.ServiceBus。根据我的测试,您可以利用以下代码来捕获异常,如下所示:

try
{
    await _queueClient
        .SendAsync(new Message(Encoding.UTF8.GetBytes("hello world")))
        .ContinueWith(t =>
        {
            Console.WriteLine(t.Status + "," + t.IsFaulted + "," + t.Exception.InnerException);
        }, TaskContinuationOptions.OnlyOnFaulted);
    Console.WriteLine("Done");
}
catch (Exception e)
{
    Console.WriteLine(e);
}

如果网络中断,您可以捕获异常如下:

【讨论】:

  • 它有效,但我只是想知道如果用户在 SendAsync 之后立即关闭应用程序,ContinueWith 中的语句是否会被执行?通常 SendAsync 需要一点时间才能失败。
猜你喜欢
  • 1970-01-01
  • 2013-07-23
  • 2015-02-25
  • 2015-06-26
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
  • 2015-08-11
  • 2012-10-19
相关资源
最近更新 更多