Make OkHttpConnectionFactory raise MwIOException when a non-suppressed API call returns an error

This commit is contained in:
Ted Gilbert 2025-10-24 20:29:52 +11:00
parent aae9d4a387
commit ea7f0770c5
4 changed files with 41 additions and 2 deletions

View file

@ -1,7 +1,11 @@
package fr.free.nrw.commons
import androidx.annotation.VisibleForTesting
import fr.free.nrw.commons.wikidata.GsonUtil
import fr.free.nrw.commons.wikidata.cookies.CommonsCookieJar
import fr.free.nrw.commons.wikidata.mwapi.MwErrorResponse
import fr.free.nrw.commons.wikidata.mwapi.MwIOException
import fr.free.nrw.commons.wikidata.mwapi.MwLegacyServiceError
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
@ -86,16 +90,25 @@ private class UnsuccessfulResponseInterceptor : Interceptor {
rsp.peekBody(ERRORS_PREFIX.length.toLong()).use { responseBody ->
if (ERRORS_PREFIX == responseBody.string()) {
rsp.body.use { body ->
throw IOException(body!!.string())
val bodyString = body!!.string()
throw MwIOException(
"MediaWiki API returned error: $bodyString",
GsonUtil.defaultGson.fromJson(
bodyString,
MwErrorResponse::class.java
).error!!,
)
}
}
}
} catch (e: IOException) {
} catch (e: MwIOException) {
// Log the error as debug (and therefore, "expected") or at error level
if (suppressErrors) {
Timber.d(e, "Suppressed (known / expected) error")
} else {
Timber.e(e)
throw e
}
}
return rsp

View file

@ -0,0 +1,7 @@
package fr.free.nrw.commons.wikidata.mwapi
import fr.free.nrw.commons.wikidata.model.BaseModel
class MwErrorResponse : BaseModel() {
val error: MwLegacyServiceError? = null
}

View file

@ -0,0 +1,5 @@
package fr.free.nrw.commons.wikidata.mwapi
import java.io.IOException
class MwIOException(string: String, val error: MwLegacyServiceError) : IOException(string)

View file

@ -0,0 +1,14 @@
package fr.free.nrw.commons.wikidata.mwapi
import fr.free.nrw.commons.wikidata.model.BaseModel
class MwLegacyServiceError : BaseModel() {
val code: String? = null
private val info: String? = null
val title: String
get() = code ?: ""
val details: String
get() = info ?: ""
}