You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin挂起函数中无法捕获Pulsar的CompletionException,如何解决?

Pulsar主题分区数获取中的异常捕获问题

我的最终目标是获取Pulsar主题的分区数,在尝试替代方案时遇到异常打印无法拦截的问题。

我采用的临时方案是:遍历预设的最大分区数,尝试创建Reader直到抛出异常,代码如下:

for (i in 0..MAX_NUM_PARTITIONS) {
    val topicPartition = "$topic-partition-$i"
    var partitionReader: Reader<ByteArray>? = null
    try {
        partitionReader =
            client
                .newReader(BYTES)
                .startMessageId(MessageId.latest)
                .topic(topicPartition)
                .create()
    } catch (e: Exception) {
        // TODO: This still prints a CompletionException error to the console unnecessarily.
        // Either catch that or calculate # partitions in a cleaner way.
        break
    }

    if (partitionReader != null) {
        readers.add(partitionReader)
    }
}

但控制台仍会打印以下异常:

java.util.concurrent.CompletionException:
org.apache.pulsar.client.api.PulsarClientException$NotAllowedException:
{"errorMsg":"Illegal topic partition name ...

即使添加了try-catch块,该异常还是会输出。我希望能捕获并阻止它打印,想知道:

  • 出现这种情况的原因是什么?
  • 是否和Kotlin协程有关?(代码运行在suspend函数中)
  • 该异常是不是Pulsar API内部抛出的,无法阻止打印?

更新:完整错误信息包含冗长的CompletionException堆栈,我不想让这些内容打印出来,以优化控制台调试体验。

内容的提问来源于stack exchange,提问作者dmonopoly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 15:12:35