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

如何避免kotlinx.html异常时try块标签出现在输出中

Kotlinx.html 异常时避免输出已创建的标签

kotlinx.html的appendHTML()属于流式渲染API,它会在你创建每个标签(如<div>、<a>)的同时,立刻将对应的HTML代码写入输出流(比如示例中的System.out)。这种设计下,一旦标签被创建并写入流,后续抛出异常也无法撤回已经输出的内容,这就是你看到异常块内标签仍会出现在输出里的原因。

方案1:先在内存构建完整DOM,确认无异常再输出

利用createHTMLDocument()在内存中构建HTML文档树,只有当整个构建过程无异常时,才将文档序列化为字符串输出;如果抛出异常,则直接构建异常处理对应的HTML内容。

import kotlinx.html.ATarget
import kotlinx.html.a
import kotlinx.html.body
import kotlinx.html.div
import kotlinx.html.html
import kotlinx.html.createHTMLDocument

fun main() {
    val htmlContent = try {
        // 尝试构建目标HTML结构
        createHTMLDocument().html {
            body {
                div {
                    a("https://kotlinlang.org") {
                        target = ATarget.blank
                        +"Main site"
                        throw RuntimeException("test")
                    }
                }
            }
        }.serialize(true) // 序列化为格式化后的HTML字符串
    } catch (e: RuntimeException) {
        // 异常时构建错误处理的HTML
        createHTMLDocument().html {
            body {
                +"Exception handled"
            }
        }.serialize(true)
    }
    println(htmlContent)
}

方案2:用临时流缓存内容,异常时丢弃缓存

通过临时输出流缓存try块内的渲染内容,只有当整个块执行无异常时,才将缓存内容写入主输出流;异常时直接输出错误处理内容,丢弃缓存。

import kotlinx.html.ATarget
import kotlinx.html.a
import kotlinx.html.body
import kotlinx.html.div
import kotlinx.html.html
import kotlinx.html.stream.appendHTML
import java.io.ByteArrayOutputStream
import java.io.PrintStream

fun main() {
    val mainOut = System.out
    try {
        val tempOut = ByteArrayOutputStream()
        // 将渲染内容写入临时流
        PrintStream(tempOut).appendHTML().html {
            body {
                div {
                    a("https://kotlinlang.org") {
                        target = ATarget.blank
                        +"Main site"
                        throw RuntimeException("test")
                    }
                }
            }
        }
        // 无异常时将临时流内容输出到主控制台
        mainOut.print(tempOut.toString())
    } catch (e: RuntimeException) {
        // 异常时直接输出错误处理内容
        mainOut.appendHTML().html {
            body {
                +"Exception handled"
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:42:49