c# - 无法连接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
解决方案
要在您的应用程序中获取实际异常,您需要添加.SetErrorHandler()
:
ProducerBuilder<string, string> _kafkaProducer = new ProducerBuilder<string, string>(_configKafka);
using (var kafkaProducer = _kafkaProducer.SetErrorHandler((producer, error) =>
{
//You can handle error right here
}).Build())
error.Reason包含错误信息
推荐阅读
- scala - rdd.count,count via spark sql的结果是一样的,但是和hive sql的count结果是不一样的
- mysql - 如果目标在一张表中而活动在另一张表中,如何显示实现不同目标的进度
- python - 删除数字及其后面的任何特殊字符或字母(来自邮政地址)
- android - Android InAppBillingV3 购买并检查商品是否已购买
- c++ - 搜索和限制特定文件类型 VS2017
- ruby-on-rails - Ruby(或 Rails)类在单线程执行期间会丢失其 object_id 吗?
- sql - 如何在一列中显示两个表之一中的一个元素
- forms - 无效表单的适当状态代码
- excel - 使用键 VBA 获取集合内的对象
- angular - 过滤管工作不正常 角度 7