Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception from a Composable

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!

like image 484
BerHug Avatar asked Nov 15 '25 12:11

BerHug


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

like image 163
Shlomi Katriel Avatar answered Nov 18 '25 07:11

Shlomi Katriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!