Skip to content

Commit cf5e95b

Browse files
authored
simplify error response adapter (#131)
1 parent e321953 commit cf5e95b

File tree

2 files changed

+3
-16
lines changed

2 files changed

+3
-16
lines changed

src/commonMain/kotlin/co/pokeapi/pokekotlin/PokeApi.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,7 @@ public fun PokeApi(
600600
configure()
601601
install(HttpCache) { cacheStorage?.let { privateStorage(it) } }
602602
install(ContentNegotiation) { json(PokeApiJson, ContentType.Any) }
603+
expectSuccess = true
603604
}
604605
)
605606
.converterFactories(ResultConverter.Factory)

src/commonMain/kotlin/co/pokeapi/pokekotlin/internal/ResultConverter.kt

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,21 @@ import de.jensklingenberg.ktorfit.converter.Converter
55
import de.jensklingenberg.ktorfit.converter.KtorfitResult
66
import de.jensklingenberg.ktorfit.converter.TypeData
77
import io.ktor.client.call.body
8-
import io.ktor.client.plugins.ClientRequestException
9-
import io.ktor.client.plugins.RedirectResponseException
10-
import io.ktor.client.plugins.ResponseException
11-
import io.ktor.client.plugins.ServerResponseException
128
import io.ktor.client.statement.HttpResponse
13-
import io.ktor.client.statement.bodyAsText
149
import io.ktor.http.isSuccess
1510

1611
internal class ResultConverter(private val typeData: TypeData) :
1712
Converter.SuspendResponseConverter<HttpResponse, Result<Any>> {
1813

19-
private suspend fun HttpResponse.toException(): Throwable {
20-
val exceptionResponseText = runCatching { bodyAsText() }.getOrElse { "<body failed decoding>" }
21-
return when (status.value) {
22-
in 300..399 -> RedirectResponseException(this, exceptionResponseText)
23-
in 400..499 -> ClientRequestException(this, exceptionResponseText)
24-
in 500..599 -> ServerResponseException(this, exceptionResponseText)
25-
else -> ResponseException(this, exceptionResponseText)
26-
}
27-
}
28-
2914
override suspend fun convert(result: KtorfitResult): Result<Any> {
3015
return when (result) {
3116
is KtorfitResult.Failure -> Result.failure(result.throwable)
3217
is KtorfitResult.Success -> {
3318
when {
3419
result.response.status.isSuccess() ->
3520
Result.success(result.response.body(typeData.typeArgs.first().typeInfo))
36-
else -> Result.failure(result.response.toException())
21+
// we configure the client with expectSuccess
22+
else -> error("impossible: " + result.response)
3723
}
3824
}
3925
}

0 commit comments

Comments
 (0)