Skip to content

Commit

Permalink
add ThrowableCallError / use in PageSizeDataSource
Browse files Browse the repository at this point in the history
  • Loading branch information
kroegerama committed Jan 9, 2024
1 parent 9296a3c commit 360dcbb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,18 @@ data class IOError(
data class UnexpectedError(
val cause: Throwable
) : CallError

data class ThrowableCallError(
val delegate: CallError
) : Throwable(
message = when (delegate) {
is HttpError -> "HTTP ${delegate.code}"
is IOError -> delegate.cause.message
is UnexpectedError -> delegate.cause.message
},
cause = when (delegate) {
is HttpError -> null
is IOError -> delegate.cause
is UnexpectedError -> delegate.cause
}
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ import androidx.paging.PagingState
import androidx.paging.cachedIn
import com.kroegerama.kaiteki.flow.UpdatableFlow
import com.kroegerama.kaiteki.flow.updatable
import com.kroegerama.kaiteki.retrofit.arrow.HttpError
import com.kroegerama.kaiteki.retrofit.arrow.IOError
import com.kroegerama.kaiteki.retrofit.arrow.ThrowableCallError
import com.kroegerama.kaiteki.retrofit.arrow.UnexpectedError
import kotlinx.coroutines.CancellationException
import retrofit2.Response
import timber.log.Timber
import java.io.IOException

abstract class PageSizeDataSource<R : Any, T : Any> : PagingSource<Int, T>() {

Expand All @@ -29,7 +33,15 @@ abstract class PageSizeDataSource<R : Any, T : Any> : PagingSource<Int, T>() {
val response = makeCall(page, size)

if (!response.isSuccessful) {
LoadResult.Error(IllegalStateException("Response code was ${response.code()}"))
LoadResult.Error(
ThrowableCallError(
HttpError(
code = response.code(),
message = response.message(),
body = response.errorBody()
)
)
)
} else {
val responseBody = response.body()!!
val data = responseBody.extractData()
Expand All @@ -44,8 +56,14 @@ abstract class PageSizeDataSource<R : Any, T : Any> : PagingSource<Int, T>() {
if (e is CancellationException) {
throw e
}
Timber.w(e)
LoadResult.Error(e)
LoadResult.Error(
ThrowableCallError(
when (e) {
is IOException -> IOError(e)
else -> UnexpectedError(e)
}
)
)
}

abstract suspend fun makeCall(page: Int, size: Int): Response<out R>
Expand Down

0 comments on commit 360dcbb

Please sign in to comment.