无法连接到Kafka集群时也不例外

时间:2019-08-08 07:51:15

标签: c# error-handling .net-core apache-kafka confluent-kafka

当程序无法连接到kafka群集时,我无法获得异常。 该代码在控制台日志中输出异常,但我需要它引发异常。我正在使用此C#库: https://github.com/confluentinc/confluent-kafka-dotnet

ProducerConfig _configKafka = new ProducerConfig { BootstrapServers ="localhost:9092/" };

ProducerBuilder<string, string> _kafkaProducer = new ProducerBuilder<string, string>(_configKafka);
using (var kafkaProducer = _kafkaProducer.Build())
{

    try
    {
        var dr = kafkaProducer.ProduceAsync("Kafka_Messages", new Message<string, string> { Key = null, Value = $"message {i++}" });
        dr.Wait(TimeSpan.FromSeconds(10));

        if(dr.Exception!=null)
        {
            Console.WriteLine($"Delivery failed:");
        }

        var status = dr.Status;

        //Console.WriteLine($"Delivered '{dr.Value}' to '{dr.TopicPartitionOffset}'");
    }

    catch (ProduceException<Null, string> e)
    {
        Console.WriteLine($"Delivery failed: {e.Error.Reason}");
    }
}

以下是confluent-kafka在控制台中显示的错误:

%3|1565248275.024|FAIL|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: localhst:9092/bootstrap: Failed to resolve 'localhst:9092': No such host is known.  (after 2269ms in state CONNECT)
%3|1565248275.024|ERROR|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: localhst:9092/bootstrap: Failed to resolve 'localhst:9092': No such host is known.  (after 2269ms in state CONNECT)
%3|1565248275.025|ERROR|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: 1/1 brokers are down

1 个答案:

答案 0 :(得分:0)

要在您的应用程序中获取实际的异常,您需要添加$ cat example.txt set example='test'

.SetErrorHandler()

错误。原因包含错误消息