In my case, I'm requesting a GitHub API, if I request a lot of data, I might get a 403 error, while if I run out of requested data, GitHub will return me a 422 Unprocessable Entity. So I want to prompt the user on the UI based on this whether it is rate limited by the API or there is no new data.
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, EventWithRepoInfo> {
val position = params.key ?: GITHUB_STARTING_PAGE_INDEX
return try {
val receivedEvents = network.receivedEvents(token, network.getUserInfo(token).login, position, params.loadSize)
val eventWithRepoInfo: MutableList<EventWithRepoInfo> = mutableListOf()
val nextKey = if (receivedEvents.isEmpty()) {
null
} else {
position + (params.loadSize / NETWORK_PAGE_SIZE)
}
nextKey?.let {
receivedEvents.forEach {
eventWithRepoInfo.add(EventWithRepoInfo(it, ktorClient.getRepoInfo(token, it.repo.url)))
}
}
LoadResult.Page(
data = eventWithRepoInfo,
prevKey = if (position == GITHUB_STARTING_PAGE_INDEX) null else position - 1,
nextKey = nextKey
)
} catch (exception: IOException) {
exception.printStackTrace()
return LoadResult.Error(exception)
} catch (exception: HttpException) {
exception.printStackTrace()
return LoadResult.Error(exception)
}
}
So I want to judge whether it is 403 or 422 in this place. If it is 422, it will show that there is no more data, and 403 will prompt the user that the api is rate-limited.
LazyColumn {
events.apply {
when {
loadState.append is LoadState.Loading -> {
item {
Text("loading")
}
}
}
// I want to show different things here depending on different error codes
loadState.append is LoadState.Error -> {
item {
LargeButton(onClick = { events.retry() }) {
Text("loading error, retry.")
}
}
}
}
}
}
There's a simple way to find out what kind of error has occurred, hope following code is helpful.
events.apply {
when {
/** Showing error state */
loadState.refresh is LoadState.Error -> {
val e = loadState.refresh as LoadState.Error
val message = ""
if (e.error is UnknownHostException) {
message = // Your message
} else if (e.error is /*Exception*/){
message = // Your message
}
item {
ErrorView(message)
}
}
/** Showing error state */
loadState.append is LoadState.Error -> {
val e = loadState.refresh as LoadState.Error
val message = ""
if (e.error is UnknownHostException) {
message = // Your message
} else if (e.error is /*Exception*/){
message = // Your message
}
item {
ErrorView(message)
}
}
}
}