Kotlin Multiplatform Mobile:如何处理iOS中的错误(网络,数据库等)? [英] Kotlin Multiplatform Mobile: How to handle errors (network, db, etc.) in iOS?

查看:81
本文介绍了Kotlin Multiplatform Mobile:如何处理iOS中的错误(网络,数据库等)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有发出网络请求并将结果写入SQLDelight数据库的功能:

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

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

在Xcode的iOS项目中,我看到此函数已转换为具有(KotlinUnit ?, Error?)->类型的completedHandler的函数.无效.

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

在我的情况下,错误类型只有1个可见属性- localizedDescription .如果我强制转换为 NSError ,那么我可以获得更多可见字段,但它们都无济于事.

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.

我在日志中看到, Ktor http客户端中的每个错误在Swift中都作为 Error 抛出.这使得很难知道抛出了哪种错误.

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.

在某些情况下,我希望能够看到错误类型并做出不同的反应.例如,如果是网络不可用错误,则显示带有翻译的我的自定义错误文本,或者如果是401错误,则将用户发送到身份验证页面,500显示其他文本,等等.

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.

对于Android应用程序,我想我可以转发这些异常,并且仍然能够键入check或访问有关错误的更多数据.但我不知道该如何处理iOS应用程序.理想情况下,该解决方案应该在两个平台上都能很好地工作.

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.

处理iOS和Android中的网络错误或从多平台项目中的共享模块抛出的任何错误/异常的最佳实践是什么?

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?

推荐答案

您可以使用 MVP 体系结构,并让 Presenter 组件处理这些错误,它只是表明到要去的地方.

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.

类似的东西:

shared/MyPresenter.kt

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

通过这种方法,您将从平台Views中消除该责任.

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

一个好的指导性项目是: https://github.com/jarroyoesp/KotlinMultiPlatform

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

这篇关于Kotlin Multiplatform Mobile:如何处理iOS中的错误(网络,数据库等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆