Android中基于Arrow Either<L,R>的错误建模优化方案咨询
解决Arrow Either类型化错误的冗余问题
核心思路:通过密封接口继承复用通用错误
Kotlin的密封接口支持继承,我们可以把授权这类通用错误抽成独立的密封接口,让任务专属的错误接口继承它,这样既保留了每个任务错误的类型唯一性,又避免了重复定义通用错误。
具体实现步骤
- 定义通用错误密封接口
sealed interface CommonError { data object Unauthorized : CommonError // 授权错误 data object NetworkError : CommonError // 网络错误 data object ServerError : CommonError // 服务端错误 }
- 让任务专属错误继承通用错误
修改你原有的错误定义,让它们继承CommonError:
sealed interface BookFlightError : CommonError { data class PaymentFailed(val cause: String) : BookFlightError } sealed interface SignUpError : CommonError { data object UsernameNotAvailable : SignUpError data object UserAlreadyExists : SignUpError }
- 在Either中使用
现在每个任务的错误类型自动包含了通用错误,比如订机票的操作可以定义为:
fun bookFlight(): Either<BookFlightError, BookingConfirmation> { // 实现逻辑,可返回CommonError子类(如Unauthorized)或BookFlightError子类(如PaymentFailed) }
- 错误处理示例
处理错误时,用when表达式可以同时覆盖通用和专属错误:
val result = bookFlight() result.fold( ifLeft = { error -> when (error) { is CommonError.Unauthorized -> handleUnauthorized() is CommonError.NetworkError -> handleNetworkError() is BookFlightError.PaymentFailed -> handlePaymentFailed(error.cause) is CommonError.ServerError -> handleServerError() } }, ifRight = { confirmation -> handleBookingSuccess(confirmation) } )
额外优化:提取通用错误处理逻辑
如果多个任务的通用错误处理逻辑一致,可以把通用错误的处理抽成单独函数,减少重复代码:
fun handleCommonError(error: CommonError) { when (error) { is CommonError.Unauthorized -> handleUnauthorized() is CommonError.NetworkError -> handleNetworkError() is CommonError.ServerError -> handleServerError() } } // 调用时 result.fold( ifLeft = { error -> if (error is CommonError) { handleCommonError(error) } else { when (error) { is BookFlightError.PaymentFailed -> handlePaymentFailed(error.cause) } } }, ifRight = { ... } )
内容的提问来源于stack exchange,提问作者Neil
相关产品推荐
相关产品推荐

