david.bilik
11/21/2020, 5:19 PM{
"status": "OK",
"data": { //my data }
}
but in the case of errors the response is still http status code 200 but body looks like
{
"status": "Error",
"description": "Invalid email address",
"error_code": 0,
"data": []
}
I have a generic class ApiResponse<T>
looking like
class ApiResponse<T>(
val data: T?,
val status: String?,
@Json(name = "error_code") val errorCode: Int?,
@JvmField val description: String? = null
)
and I am parsing it through Moshi through function similar to
fun <T> parseResponse(moshi: Moshi, body:String, type: Class<T>) : ApiResponse<T> {
val apiResponseType = Types.newParameterizedType(ApiResponse::class.java, type)
val toReturn = moshi.adapter<ApiResponse<T>>(apiResponseType).fromJson(body)
if (toReturn.errorCode != null) {
throw ApiResponseErrorException(toReturn.errorCode, toReturn.description ?: "")
}
return toReturn
}
which works fine in most of the cases but the problem is that the field data
is returned as empty array in the case of error, which results in failing JSON parsing if the type of ApiResponse
is not an list.. My first thought was to create a custom adapter for ApiResponse
class and in the case of status == "Error"
i would not parse the data at all and just return the exception but i don’t know how to write such an adapter because I don’t have information about the generic type of data
in the happy scenarios. What is the best way to deal with that without ugly try/catches?