|
@@ -18,14 +18,16 @@ import java.lang.reflect.Type
|
|
|
import kotlin.reflect.KType
|
|
|
|
|
|
class SerializationConverter(
|
|
|
- val success: String = "0",
|
|
|
- val code: String = "code",
|
|
|
- val message: String = "msg"
|
|
|
+ val success: String = "0",
|
|
|
+ val code: String = "code",
|
|
|
+ val message: String = "msg"
|
|
|
) : NetConverter {
|
|
|
|
|
|
- private val jsonDecoder = Json {
|
|
|
- ignoreUnknownKeys = true // JSON和数据模型字段可以不匹配
|
|
|
- coerceInputValues = true // 如果JSON字段是Null则使用默认值
|
|
|
+ companion object {
|
|
|
+ val jsonDecoder = Json {
|
|
|
+ ignoreUnknownKeys = true // JSON和数据模型字段可以不匹配
|
|
|
+ coerceInputValues = true // 如果JSON字段是Null则使用默认值
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
override fun <R> onConvert(succeed: Type, response: Response): R? {
|
|
@@ -37,20 +39,26 @@ class SerializationConverter(
|
|
|
code in 200..299 -> { // 请求成功
|
|
|
val bodyString = response.body?.string() ?: return null
|
|
|
val kType = response.request.kType
|
|
|
- ?: throw ConvertException(response, "Request does not contain KType")
|
|
|
+ ?: throw ConvertException(response, "Request does not contain KType")
|
|
|
return try {
|
|
|
val json = JSONObject(bodyString) // 获取JSON中后端定义的错误码和错误信息
|
|
|
if (json.getString(this.code) == success) { // 对比后端自定义错误码
|
|
|
bodyString.parseBody<R>(kType)
|
|
|
} else { // 错误码匹配失败, 开始写入错误异常
|
|
|
- val errorMessage = json.optString(message, NetConfig.app.getString(com.drake.net.R.string.no_error_message))
|
|
|
+ val errorMessage = json.optString(
|
|
|
+ message,
|
|
|
+ NetConfig.app.getString(com.drake.net.R.string.no_error_message)
|
|
|
+ )
|
|
|
throw ResponseException(response, errorMessage)
|
|
|
}
|
|
|
} catch (e: JSONException) { // 固定格式JSON分析失败直接解析JSON
|
|
|
bodyString.parseBody<R>(kType)
|
|
|
}
|
|
|
}
|
|
|
- code in 400..499 -> throw RequestParamsException(response, code.toString()) // 请求参数错误
|
|
|
+ code in 400..499 -> throw RequestParamsException(
|
|
|
+ response,
|
|
|
+ code.toString()
|
|
|
+ ) // 请求参数错误
|
|
|
code >= 500 -> throw ServerResponseException(response, code.toString()) // 服务器异常错误
|
|
|
else -> throw ConvertException(response)
|
|
|
}
|