Skip to content

Instantly share code, notes, and snippets.

View kelvinkioko's full-sized avatar

Kelvin Kioko kelvinkioko

View GitHub Profile
@kelvinkioko
kelvinkioko / ExceptionHandler.kt
Created July 17, 2021 19:07
Exception handler kt
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
Timber.e(exception)
val exceptionError = exception.handleThrowable()
val message = if (exceptionError.errors != null && exceptionError.errors.phone.isNotEmpty())
"${exceptionError.message} ${exceptionError.errors.phone[0]}"
else
exceptionError.message
_uiState.postValue(AuthUIState.Error(message))
}
@kelvinkioko
kelvinkioko / Throwable.kt
Created July 17, 2021 19:00
Exception throwable handler
fun Throwable.handleThrowable(): ApiError {
Timber.e(this)
return if (this is UnknownHostException)
ApiError(message = "Connection error")
else if (this is HttpException && this.code() == 403)
ApiError(message = "Not authorized")
else if (this is HttpException && this.code() == 422)
extractExceptionMessage(exception = this)!!
else if (this is SocketTimeoutException)
ApiError(message = "Please check your connectivity and try again")
@kelvinkioko
kelvinkioko / ExtractExceptionMessage.kt
Last active July 17, 2021 18:53
Extract exception message from the error body
fun extractExceptionMessage(exception: HttpException): ApiError? {
val adapter: JsonAdapter<ApiError> = Moshi.Builder().build().adapter(ApiError::class.java).lenient()
exception.response()?.run {
errorBody()?.let {
val errorJson = it.string()
return if (!errorJson.contains("{"))
ApiError(message = errorJson)
else
adapter.fromJson(errorJson)
}
@kelvinkioko
kelvinkioko / ApiError.kt
Created July 17, 2021 18:44
Data class to handle error formatting
@JsonClass(generateAdapter = true)
data class ApiError(
@Json(name = "message")
val message: String = "",
@Json(name = "errors")
val errors: ApiErrorMessages? = null
)
@JsonClass(generateAdapter = true)
data class ApiErrorMessages(
{"message":"The given data was invalid.","errors":{"phone":["The phone has already been taken."]}}
private val exceptionHandler = CoroutineExceptionHandler { _, exception ->
Timber.e(exception)
}
fun validateUser(emailAddress: String, password: String) {
viewModelScope.launch(exceptionHandler) {
withContext(Dispatchers.IO) {
val response = api.signUp(
email_address = emailAddress,
password = password
@kelvinkioko
kelvinkioko / FANUtilClass.kt
Created December 12, 2020 18:04
Facebook audience network util class
import android.content.Context
import com.facebook.ads.Ad
import com.facebook.ads.AdError
import com.facebook.ads.AdSize
import com.facebook.ads.AdView
import com.facebook.ads.InterstitialAd
import com.facebook.ads.InterstitialAdListener
fun setupBannerAdView(context: Context): AdView {
return AdView(context, "632419430786378_632419467453041", AdSize.BANNER_HEIGHT_50)