Nie Selam
Nie Selam

Reputation: 1451

propagating errors from query flow to out

I admit...the design have issues but looking for a quick solution for now. I have this code

try {
val query = query goes here
val queryFlow =
                query
                    .queryChangeFlow()
                    .map { queryChange ->
                        val err = queryChange.error
                        if (err != null) {
                            throw err //works as intended
                        }

                        val data =
                            queryChange.results?.allResults()?.mapNotNull { result ->
                                val cblDocument = result.getDictionary(0)
                                val doc = cblDocument?.toDataClass<UserData>()
                                doc
                            } ?: emptyList()
                        data
                    }.asLiveData()
            return queryFlow.asFlow()
        } catch (e: Exception) {
            Log.e("MLG", e)
            throw e
        }

Now toDataClass might be unable to parse the document, thus crashing the app. I want to catch it instead and propogate it to the outer catch block. If toDataClass is okay, the app works well.

I am struggling to pass the error from inside query flow to the outside while keeping the return and implementaiton of the method as is due to lack of time.

Any ideas please?

Upvotes: 0

Views: 25

Answers (1)

G. Blake Meike
G. Blake Meike

Reputation: 6715

The problem is that the error you throw is being thrown on a completely different thread, with a completely different call stack, from the thread that executes the "try" block.

A common solution to this is to return some kind of Optional that contains either the data or the Exception.

... and, as I've mentioned elsewhere, it is kind of odd to convert a Flow to LiveData and then back to a Flow...

Upvotes: 1

Related Questions