chinwag-android/app/src/main/java/com/keylesspalace/tusky/util/ThrowableExtensions.kt
Konrad Pozniak 5192fb08a5
upgrade ktlint plugin to 12.0.3 (#4169)
There are some new rules, I think they mostly make sense, except for the
max line length which I had to disable because we are over it in a lot
of places.

---------

Co-authored-by: Goooler <wangzongler@gmail.com>
2024-01-04 17:00:55 +01:00

44 lines
1.5 KiB
Kotlin

package com.keylesspalace.tusky.util
import android.content.Context
import com.keylesspalace.tusky.R
import java.io.IOException
import org.json.JSONException
import org.json.JSONObject
import retrofit2.HttpException
/**
* checks if this throwable indicates an error causes by a 4xx/5xx server response and
* tries to retrieve the error message the server sent
* @return the error message, or null if this is no server error or it had no error message
*/
fun Throwable.getServerErrorMessage(): String? {
if (this is HttpException) {
val errorResponse = response()?.errorBody()?.string()
return if (!errorResponse.isNullOrBlank()) {
try {
JSONObject(errorResponse).getString("error")
} catch (e: JSONException) {
null
}
} else {
null
}
}
return null
}
/** @return A drawable resource to accompany the error message for this throwable */
fun Throwable.getDrawableRes(): Int = when (this) {
is IOException -> R.drawable.errorphant_offline
is HttpException -> R.drawable.errorphant_offline
else -> R.drawable.errorphant_error
}
/** @return A string error message for this throwable */
fun Throwable.getErrorString(context: Context): String = getServerErrorMessage() ?: when (this) {
is IOException -> context.getString(R.string.error_network)
else -> context.getString(R.string.error_generic)
}
fun Throwable.isHttpNotFound(): Boolean = (this as? HttpException)?.code() == 404