ceving
ceving

Reputation: 23863

How to catch an error in Jetpack compose?

I tried to catch application errors in this way:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            try {
                MyApp()
            }
            catch (t: Throwable) {
                Text(t.message ?: "Error", fontSize = 24.sp)
                Text(t.stackTraceToString(), fontFamily = FontFamily.Monospace)
            }
        }
    }
}

But it does not compile:

Try catch is not supported around composable function invocations.

WTF?

What else should I use?

Upvotes: 12

Views: 8123

Answers (1)

Muhammad Uzair
Muhammad Uzair

Reputation: 45

@Composable
fun MyScreen() {
    val data = try {
        loadData()
    } catch (error: Throwable) {
        // Handle the error here
        null
    }

    if (data != null) {
        // Render the data
    } else {
        // Render an error message or retry button
    }
}

To use the catch operator, you can call it on a Composable function and pass in a lambda function to handle the error. The lambda function should take a single parameter of type Throwable, which represents the error that occurred. Inside the lambda function, you can perform any necessary error handling, such as displaying an error message or retrying the failed operation.

Upvotes: 2

Related Questions