Throw exception from a Composable

Viewed 261

I wrote a simple composable that provides an IconButton.

@Composable
fun MenuIcon(
    @DrawableRes iconRes: Int,
    contentDescription: String,
    onClick: () -> Unit,
) {
    if (contentDescription.isEmpty()) {
        throw IllegalArgumentException("contentDescription is mandatory and should not be empty.")
    }
    // I also tried assert(contentDescription.isNotEmpty())

    IconButton(onClick = onClick) {
        Image(
            painter = painterResource(id = iconRes),
            contentDescription = contentDescription,
        )
    }
}

In our project, we want to force our developers to provide a content description for accessibility purpose. So I add a simple check to throw an exception if contentDescription is empty.

The problem is the following: when exception is thrown, in Logcat, I get another exception that did not point on my Composable:

java.lang.IllegalStateException: pending composition has not been applied
[...]

It will not help developers using my composable to find the problem... Is there a solution to display my error message?

Thanks!

1 Answers

Throw exception from thread, this way you're making sure that nothing in stack catches it and messing around with your intended crash:

if (contentDescription.isEmpty()) {
    thread(name = "WatchdogThread") {
        throw IllegalArgumentException("...")
    }
}

Don't worry about optimization (not using thread pool or coroutines) since you only expect content description to be empty on debug builds.

Cheers

Related