Android 使用Moshi处理错误响应
在我的Android应用程序中,发送一些注册凭据后,我从服务器获得以下JSON输出:Android 使用Moshi处理错误响应,android,json,moshi,custom-error-handling,Android,Json,Moshi,Custom Error Handling,在我的Android应用程序中,发送一些注册凭据后,我从服务器获得以下JSON输出: { "response":"successfully registered new user", "email":"testing@gmail.com", "username":"testing", "id":9, "token":"98d26
{
"response":"successfully registered new user",
"email":"testing@gmail.com",
"username":"testing",
"id":9,
"token":"98d26160e624a0b762ccec0cb561df3aeb131ff5"
}
我使用带有以下数据类的Moshi
库对此进行了建模:
@JsonClass(generateAdapter = true)
data class Account (
@Json(name = "id")
val account_id : Long,
@Json(name="email")
val account_email: String,
@Json(name="username")
val account_username: String,
@Json(name="token")
val account_authtoken : String,
@Json(name="response")
val account_response : String
)
一切正常。现在我想处理错误案例。当我收到一个错误(比方说,我想注册的电子邮件已经存在)时,我应该得到一个JSON输出,如下所示:
// what the app gets when there is some error with the credentials
// e.g. email exists, username exists etc.
{
"error_message" : "The email already exists",
"response": "Error"
}
// I get the idea for this from https://phauer.com/2019/sealed-classes-exceptions-kotlin/
sealed class NetworkResult<out R> {
data class Success<out T>(val data: T) : NetworkResult<T>()
data class Error(val exception: Exception) : NetworkResult<Nothing>()
}
执行请求的方法如下所示:
override suspend fun register(email: String, userName: String, password: String, passwordToConfirm: String): NetworkResult<Account> {
// make the request
val response = authApi.register(email, userName, password, passwordToConfirm)
// check if response is successful
return if(response.isSuccessful){
try {
// wrap the response into NetworkResult.Success
// response.body() contains the Account information
NetworkResult.Success(response.body()!!)
}
catch (e: Exception){
NetworkResult.Error(IOException("Error occurred during registration!"))
}
} else {
NetworkResult.Error(IOException("Error occurred during registration!"))
}
}
但这不会处理我上面提到的错误的JSON输出。当应用程序获得错误JSON输出时,Moshi
抱怨帐户
数据类没有错误消息
属性,这对我来说是清楚的,因为我的帐户
数据类中没有这样的字段
我需要更改什么,以便我也可以处理任何我希望的错误情况?我知道,我可以为第二个数据类建模,并使用字段response
和Error\u message
将其称为Error
,但我的密封类NetworkResult
只接受一个类作为泛型类型
< >我能做什么? 如果在数据类中没有初始化一个字段的值,MoSHII会将其视为必填字段。
@JsonClass(generateAdapter = true)
data class Account (
@Json(name = "id")
val account_id : Long = 0,
@Json(name="email")
val account_email: String = "",
@Json(name="username")
val account_username: String = "",
@Json(name="token")
val account_authtoken : String = "",
@Json(name="response")
val account_response : String = "",
@Json(name="error_message")
val error_message : String = ""
)
这样,您就可以为成功和错误创建相同的数据类。有许多方法可以修复它,可以为错误和帐户结果添加字段和标志,也可以创建自定义Moshi适配器,或者使用映射器等辅助地映射原始结果