Kotlin Multiplatform Mobile: How to handle errors (network, db, etc.) in iOS?
Asked Answered
T

2

14

I have this function that makes a network request and writes results to SQLDelight database:

@Throws(Exception::class)
suspend fun updateData()

In iOS project in Xcode I see that this function is translated into a function with completionHandler of type (KotlinUnit?, Error?) -> Void.

In my case Error type has only 1 visible property - localizedDescription. If I cast to NSError then I can get more visible fields but none of them are of any help.

I saw in logs that every error in Ktor http client is thrown as Error in Swift. This makes it hard to know what kind of error was thrown.

I want to be able to see the error type and react differently for certain cases. For example, if it was network unavailable error, to show my custom error text with translations, or if it was 401 error send user to auth page, 500 show some other text, etc.

For Android app I guess I can just forward those exceptions and still be able to type check or access more data about error. But I don't know what to do for iOS app. The solution ideally should work great on both platforms.

What are the best practices for handling network errors in iOS and in Android or in general any error/exception that are thrown from shared module in multiplatform project?

Tormentil answered 29/12, 2020 at 21:28 Comment(3)
Maybe this documentation page is relevant here?Spooky
Manage to find a solution for this? Im also encounter the same problem as yoursFiesole
This question is so underrated, Has anybody found a solution to this? This is the real pain!Col
C
2

You can use a MVP architecture and let the Presenter component deal with these errors and it just indicates to the view where to go.

Something like that:

shared/MyPresenter.kt

// ...
when (throwable) {
    is Unauthorized -> {
        view?.showInvalidCredentials()
    }
    is Conflict -> {
        view?.showConflictAccount()
    }
    else -> {
        view?.showError(throwable)
    }                    
}

With this approach you'll remove that responsibility from the platform Views.

A good project to take as a guide is that: https://github.com/jarroyoesp/KotlinMultiPlatform

Chit answered 31/12, 2020 at 4:3 Comment(0)
A
1

You can map responses in your network layer to a Result. Often the data modelling of result is specific to your application, so can include some combination of loading/error/result by using generics or sealed classes.

You can also use the Result type in the kotlin standard library.

Adachi answered 7/3, 2021 at 23:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.