https://kotlinlang.org logo
#compose
Title
# compose
p

Per Jansson

03/29/2023, 6:21 AM
What is the recommended way to handle errors happening inside composables, i.e. the corresponding way that React handles it with ErrorBoundary? We are using a third-party library providing us a composasble, but when that sometimes errors out the whole applications crashes. I would be nice to be able to try/catch this, but that does not compile: “Try catch is not supported around composable function invocations”. Example:
Copy code
@Composable
fun MyApp() {
  ..
  ..
  ThirdPartyComposableThatSometimesErrorsOut() {
    ...
  }
}
I can’t do
Copy code
@Composable
fun MyApp() {
  ..
  ..
  try {
    ThirdPartyComposableThatSometimesErrorsOut() {
      ...
    }
  } catch (error: Throwable) {
    // Handle the error here
  }
}
👀 1
m

mgrazianodecastro

03/30/2023, 4:01 AM
This one looks hard, I don't have a runtime broken composable to test 😅, but I've tried this:
Copy code
sealed class MyErrorHandler {
    data class Ok(val content: @Composable () -> Unit): MyErrorHandler()
    object Err: MyErrorHandler()
}

fun getMyThirdPartyComposable(): MyErrorHandler {
        return try {
            MyErrorHandler.Ok {
                ComposeView(this).apply {  // get the context from somewhere
                    setContent {
                        Text(text = "Hello world.")
                    }
                }
            }

        }catch (err: Exception){
            MyErrorHandler.Err
        }
    }
}
then we would match inside the composable tree. I'm curious to see the result!
p

Per Jansson

03/30/2023, 9:44 AM
I might be doing something wrong but: 1. When I’m using it to compose the 3rd party composable that errors out, it still returns
MyErrorHandler.Ok
2. When I’m using it to compose the 3rd party composable when it works, it returns
MyErrorHandler.Ok
but does not compose anything on the screen. I’m passing in
LocalContext.current
as
context
and rendering the response from
getMyThirdPartyComposable
with something like this:
Copy code
@Composable
fun MyView() {
    val context = LocalContext.current
    val errorHandler = getMyThirdPartyComposable(context)

    when (errorHandler) {
        is MyErrorHandler.Ok -> {
            errorHandler.content()
        }
        is MyErrorHandler.Err -> {
            // handle the error
        }
    }
}
7 Views