Android领域层如何获取字符串资源且保持纯Kotlin特性?
解决方案
- Domain层仅定义异常类型,不绑定实际文案
domain层保持纯Kotlin属性,自定义异常只做类型区分,可选携带业务参数,不引入任何Android资源依赖,示例代码:
// domain层代码,无任何Android平台依赖 sealed class MyError(cause: Throwable? = null) : Exception(cause) { // 无网络异常 class NoNetworkException(cause: Throwable? = null) : MyError(cause) // 其他自定义异常可按需扩展 class AuthExpiredException(cause: Throwable? = null) : MyError(cause) class UploadFailedException(val failedCount: Int, cause: Throwable? = null) : MyError(cause) }
- Presentation层统一做异常到字符串资源的映射
Presentation层本身负责视图交互,天然可以访问Android字符串资源,在这里统一捕获/处理domain层抛出的异常,根据异常类型匹配对应多语言资源即可,示例代码:
// 放在Presentation层的异常解析工具类/ViewModel中均可 fun getErrorString(error: MyError): String { return when (error) { is MyError.NoNetworkException -> getString(R.string.no_network_available_error) is MyError.AuthExpiredException -> getString(R.string.auth_expired_tip) is MyError.UploadFailedException -> getString(R.string.upload_failed_tip, error.failedCount) } }
这个方案既满足Android原生多语言适配规则,又完全保留了domain层的平台独立性,后续新增异常只需要在domain加类型、在Presentation层加映射即可,维护成本很低。
内容的提问来源于stack exchange,提问作者العبد
相关产品推荐
相关产品推荐

