Trouble catching exception on Azure Service Bus SendAsync method

怎甘沉沦 提交于 2019-12-23 03:15:55

问题


I'm trying to use the following code to setup a failure condition, namely were there is no network path available, so the code shouldn't be able to send to the Service bus at all. I know this because I disable my network ports when I test.

I am still having trouble with the Async nature of the code though. I don't know in a console application like I have how to attach something that would log out the exception that I know should be generated.

How do I see that exception text?

        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;
        }

    }

回答1:


According to your code, I assumed that you are using the Azure Service Bus .NET Standard client library Microsoft.Azure.ServiceBus. Per my test, you could leverage the following code to capture the exception as follows:

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);
}

If the network is break, you may capture the exception as follows:



来源:https://stackoverflow.com/questions/48026671/trouble-catching-exception-on-azure-service-bus-sendasync-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!