refactor: 优化接口统一异常处理

This commit is contained in:
Quyunshuo
2021-08-26 22:32:07 +08:00
parent 0376d7729d
commit 53f8dc90d1
4 changed files with 42 additions and 28 deletions

View File

@ -1,29 +1,35 @@
package com.quyunshuo.androidbaseframemvvm.common.helper
import com.quyunshuo.androidbaseframemvvm.base.utils.toast
import kotlin.jvm.Throws
import com.quyunshuo.androidbaseframemvvm.common.helper.ResponseExceptionEnum as ExceptionType
/**
* 请求异常处理
* 响应code异常统一处理
*
* 该方法主要做两件事:
*
* - 1.做统一的code码处理
* - 2.未进行统一处理的code码会被转换为自定义异常[ResponseException]抛出
*
* 使用方式为:进行统一处理的异常进行抛出[ResponseEmptyException],未进行处理的抛出[ResponseException]
* 使用方式为:进行统一处理的异常进行抛出[ResponseEmptyException],未进行处理的code抛出[ResponseException],成功状态下执行[successBlock]
*
* @param code Int code码
* @param msg String? 错误信息
* @param successBlock suspend () -> Unit 没有异常的情况下执行的方法体 可以在此处进行数据的发射
* @throws ResponseException 未进行处理的异常会进行抛出让ViewModel去做进一步处理
*/
@Throws(ResponseException::class)
fun responseExceptionHandler(code: Int) {
suspend fun responseCodeExceptionHandler(
code: Int,
msg: String?,
successBlock: suspend () -> Unit
) {
// 进行异常的处理
when (code) {
ExceptionType.INTERNAL_SERVER_ERROR.getCode() -> {
toast(ExceptionType.INTERNAL_SERVER_ERROR.getMessage())
throw ResponseEmptyException()
}
ExceptionType.SUCCESS.getCode() -> successBlock.invoke()
}
}

View File

@ -2,15 +2,17 @@ package com.quyunshuo.androidbaseframemvvm.common.helper
import com.quyunshuo.androidbaseframemvvm.common.helper.ResponseExceptionEnum as ExceptionType
/**
* 请求响应异常主要为各种code码专门定义的异常
*
* @property type ResponseExceptionEnum 异常类型枚举,用于标记该异常的类型
* @param type ResponseExceptionEnum 异常类型枚举,用于标记该异常的类型
* @param msg String 异常信息
*
* @author Qu Yunshuo
* @since 2021/7/9 2:57 下午
*/
class ResponseException(val type: ExceptionType) : Exception()
class ResponseException(val type: ExceptionType, val msg: String) : Exception()
/**
* 空异常,表示该异常已经被处理过了,不需要再做额外处理了

View File

@ -1,5 +1,26 @@
package com.quyunshuo.androidbaseframemvvm.common.helper
/**
* 请求响应异常枚举的抽象
*
* @author Qu Yunshuo
* @since 2021/7/9 2:56 下午
*/
interface ResponseExceptionEnumCode {
/**
* 获取该异常枚举的code码
* @return Int
*/
fun getCode(): Int
/**
* 获取该异常枚举的描述
* @return String
*/
fun getMessage(): String
}
/**
* 请求响应异常的类型
*
@ -7,8 +28,15 @@ package com.quyunshuo.androidbaseframemvvm.common.helper
* @since 2021/7/9 2:55 下午
*/
enum class ResponseExceptionEnum : ResponseExceptionEnumCode {
INTERNAL_SERVER_ERROR {
override fun getCode() = 500
override fun getMessage() = "服务器内部错误"
},
// 成功
SUCCESS {
override fun getCode() = 200
override fun getMessage() = "成功"
}
}

View File

@ -1,22 +0,0 @@
package com.quyunshuo.androidbaseframemvvm.common.helper
/**
* 请求响应异常枚举的抽象
*
* @author Qu Yunshuo
* @since 2021/7/9 2:56 下午
*/
interface ResponseExceptionEnumCode {
/**
* 获取该异常枚举的code码
* @return Int
*/
fun getCode(): Int
/**
* 获取该异常枚举的描述
* @return String
*/
fun getMessage(): String
}