With kotlinx.html, exception handling looks counter-intuitive to me. In a try-catch block, tags created in the try block are still part of the HTML output even if an exception occurs. How can this be prevented.
Example code:
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
fun main() {
System.out.appendHTML().html {
body {
try {
div {
a("https://kotlinlang.org") {
target = ATarget.blank
+"Main site"
throw RuntimeException("test");
}
}
} catch (e: RuntimeException) {
+"Exception handled"
}
}
}
}
This produces:
<html>
<body>
<div><a href="https://kotlinlang.org" target="_blank">Main site</a></div>
Exception handled</body>
</html>
I wouldn't want to see the whole div-a combination.
This is expected. All code until an exception is expected to run and have the full impact of being run. We can add mechanisms to work as you're expecting, but many languages use this as an error handling pattern, Kotlin does not have a unique method of error handling.
Kotlin has built the HTML wrappers to be a DSL that is line by line adding the fields as they are interpreted. This will mean anything up until an Exception will be a part of the resulting Element.
Writing a function like this will continue to show that case.
Output:
If this functionality is not desired and you are looking for the output to be similar to:
Then you will want to adopt a pattern like:
In this I am using the scope function
with
to make the creation easier and more similar to the normal DSL calls. Then in either side of the try/catch, I add a div, because if it was a top level div in the try, it would still have everything that had been added before the exception itself. This is because of the DSL that is built into the library.If you open the
div
definition you will see thevisitAndFinalize
call, which is what is having the DSL happen on every line that is called.If you must be working with a JVM based system rather than a JS based target, you can then create a document to get the similar syntax mentioned above:
There are many ways this can be approached, but this should be one method to achieve what you are looking for
Documentation from the Library for reference: DOM-trees