user924
user924

Reputation: 12293

Kotlin null-safety is ignored when using Retrofit Gson Converter for parsing Json data (serialization)

I noticed that the following code doesn't throw expectation when server doesn't send any data I expect:

override suspend fun forgotPasswordCheckCode(phone: String, code: String): String {
    return try {
        authApi.forgotPasswordCheckCode(
            NetworkForgotPasswordCheckCodeRequest(
                phone = phone,
                code = code
            )
        ).data.verificationToken
    } catch (e: Throwable) {
        throw ... // parse http error logic, but doesn't catch it here
    }
}

repository:

override fun forgotPasswordCheckCode(phone: String, code: String): Flow<String> = flow {
    val token = authDataSource.forgotPasswordCheckCode(phone, code)
    emit(token)
}

at the domain layer I map it like this (in a use case):

inline fun <reified T> Flow<T>.wrapAsResult(): Flow<Result<T>> {
    return this
        .map<T, Result<T>> {
            Result.Success(it)
        }
        .onStart { emit(Result.Loading) }
        .catch { error ->
            Timber.e(error, "Flow")
            emit(Result.Error(error))
        }
}

Serialized data

data class NetworkForgotPasswordCheck(
    @SerializedName("verificationToken")
    val verificationToken: String,
)

data class NetworkDataResponse<T>(@SerializedName("data") val data: T)

Retrofit:

@POST("Auth/verify/sms/password/complete")
suspend fun forgotPasswordCheckCode(
    @Body checkCodeRequest: NetworkForgotPasswordCheckCodeRequest
): NetworkDataResponse<NetworkForgotPasswordCheck>

Right now we have the issue on the server side and it sends 200 HTTP-code when sms-code is invalid, yes, a backend developer should fix it, send 4** HTP code instead, but why my Android code doesn't catch nullable value? On the UI/ViewModel I get null value and then app crashes because I get Result.Success(null) basically and when try to use result.data. I didn't set String? anywhere, I set String.

<-- 200 https://.../Auth/verify/sms/password/complete (84ms)
{"data":{"message":"Unable to verify subject with given code"}}

I recently updated Kotlin from 1.8.* to 1.9.0, could it be the issue?

[versions]
kotlin = "1.9.0"
okhttpBom = "4.10.0"
retrofit = "2.9.0"

Upvotes: 0

Views: 75

Answers (0)

Related Questions