compose-multiplatform: Is there a component similar to the ErrorBoundary in React in Compose?
I need to load third-party codes while building my UI, but the third-party code may throw exceptions during the composing. Then the whole program crashes.
So I’m wondering if there is an ErrorBoundary in Compose similar to the one in React to implement child component exception catching?
I tried the following code:
@Composable
fun ErrorBoundary(content: @Composable () -> Unit) {
try {
content()
} catch (e: Throwable) {
e.printStackTrace()
}
}
But I got Try catch is not supported around composable function invocations.
Then I try to use the following very hacks code:
@Composable
@Suppress("ILLEGAL_TRY_CATCH_AROUND_COMPOSABLE", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
fun ErrorBoundary(content: @Composable () -> Unit) {
val stack = currentComposer::class.java.getDeclaredField("pendingStack").apply { isAccessible = true }
val curStack = stack.get(currentComposer)
val backing = androidx.compose.runtime.Stack::class.java.getDeclaredField("backing").apply { isAccessible = true }
val curBacking = ArrayList(backing.get(curStack) as ArrayList<*>)
try {
content()
} catch (e: Throwable) {
e.printStackTrace()
backing.set(curStack, curBacking)
}
}
@Composable
fun Test() {
ErrorBoundary {
Text("Test")
throw RuntimeException("Test Error!")
Text("Error")
}
}
@Composable
fun App() { Test() }
However, if the exception occurs in a deeper component or there is a SideEffect, the above code will not work.
Because my program will load third-party plugins as an extension, I cannot control all third-party code.
I have also tried the following code, but if an exception occurs in Canvas, the whole program will still exit.
window.exceptionHandler = WindowExceptionHandler { it.printStackTrace() }
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 23 (10 by maintainers)
I made a sample here: https://github.com/dima-avdeev-jb/compose-with-classloader