[debug] Show toast when network error occurred

This commit is contained in:
kyori19 2023-06-11 14:28:54 +09:00
parent e0126519e0
commit e63102712b
No known key found for this signature in database
GPG Key ID: F7BDE7DD42BF366A
2 changed files with 33 additions and 0 deletions

View File

@ -25,6 +25,7 @@ import com.google.gson.GsonBuilder
import com.keylesspalace.tusky.BuildConfig
import com.keylesspalace.tusky.db.AccountManager
import com.keylesspalace.tusky.json.Rfc3339DateJsonAdapter
import com.keylesspalace.tusky.network.HttpToastInterceptor
import com.keylesspalace.tusky.network.InstanceSwitchAuthInterceptor
import com.keylesspalace.tusky.network.MastodonApi
import com.keylesspalace.tusky.network.MediaUploadApi
@ -105,6 +106,7 @@ class NetworkModule {
addInterceptor(InstanceSwitchAuthInterceptor(accountManager))
if (BuildConfig.DEBUG) {
addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BASIC })
addInterceptor(HttpToastInterceptor(context))
}
}
.build()

View File

@ -0,0 +1,31 @@
package com.keylesspalace.tusky.network
import android.content.Context
import android.widget.Toast
import androidx.core.content.ContextCompat
import okhttp3.Interceptor
import okhttp3.Response
class HttpToastInterceptor(
private val context: Context,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
return runCatching { chain.proceed(request) }
.onSuccess {
if (!it.isSuccessful) {
showToast("${request.method} ${request.url}\n${it.code} ${it.message}")
}
}
.onFailure { showToast("${request.method} ${request.url}\n${it}") }
.getOrThrow()
}
private fun showToast(message: String) {
ContextCompat.getMainExecutor(context).execute {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
}