Hi, i’m dealing with a pretty “specific” http API ...
# squarelibraries
Hi, i’m dealing with a pretty “specific” http API which in OK scenarios has JSON responses like
Copy code
  "status": "OK",
  "data": { //my data }
but in the case of errors the response is still http status code 200 but body looks like
Copy code
  "status": "Error",
  "description": "Invalid email address",
  "error_code": 0,
  "data": []
I have a generic class
looking like
Copy code
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
Copy code
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
is returned as empty array in the case of error, which results in failing JSON parsing if the type of
is not an list.. My first thought was to create a custom adapter for
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
in the happy scenarios. What is the best way to deal with that without ugly try/catches?