与莫希一起处理错误响应



在我的Android应用程序中,发送一些注册凭据后,我从服务器获得以下JSON输出:

{
"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"
}

执行请求的方法如下所示:

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!"))
}
}

如果响应成功,则会将response.body()包装到NetworkResult.Success数据类中。 我的NetworkResult类是一个密封类,有两个子数据类SuccessError。 它看起来像这样:

// 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>() 
}

但这并不能处理我上面提到的错误的 JSON 输出。当应用程序收到错误 JSON 输出时,Moshi抱怨Account数据类没有error_message属性,这对我来说很清楚,因为我的Account数据类中没有这样的字段。

我需要更改什么,以便我也可以处理我希望的任何错误情况?我知道,我可以对第二个数据类进行建模,并使用字段responseerror_message调用它Error,但我的密封类NetworkResult只接受一个类作为泛型类型。

那么,我该怎么办?

如果您没有将值初始化为数据类中的字段,Moshi 会将其视为必填字段。

@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 = ""
)

像这样,您可以为成功和错误创建相同的数据类。

最新更新