-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseService.kt
89 lines (78 loc) · 3.14 KB
/
BaseService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package <YOUR_PACKAGE_NAME>
import <YOUR_PACKAGE_NAME>.R
import <YOUR_PACKAGE_NAME>.StringResourceProvider
import kotlinx.coroutines.CoroutineDispatcher
import retrofit2.HttpException
import java.io.EOFException
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException
abstract class BaseService(
private val coroutineDispatcher: CoroutineDispatcher,
private val stringResourceProvider: StringResourceProvider
) {
protected suspend fun <T> requestApiResource(apiCall: suspend () -> T): Resource<out T> {
return try {
val result = apiCall.invoke()
Resource.Data(result)
} catch (throwable: Throwable) {
when (throwable) {
is HttpException -> handleHttpExceptions(throwable)
is TimeoutException -> handleTimeOut()
is EOFException -> handleEmptyResult()
is IOException -> handleNetworkError(throwable)
else -> createUnexpectedError(throwable)
}
}
}
private fun handleNetworkError(throwable: IOException): Resource.Error {
return when (throwable) {
is SocketTimeoutException -> createDefaultResponseError(
stringResourceProvider.getString(
R.string.internet_issue_message
)
)
is UnknownHostException -> createDefaultResponseError(stringResourceProvider.getString(R.string.server_not_responding))
else -> createDefaultResponseError(stringResourceProvider.getString(R.string.internet_issue_message))
}
}
private fun handleTimeOut(): Resource.Error {
return Resource.Error(
stringResourceProvider.getString(R.string.internet_issue_message),
DEFAULT_ERROR_CODE
)
}
private fun handleEmptyResult(): Resource.Error {
return Resource.Error(
stringResourceProvider.getString(R.string.no_data_found),
DEFAULT_ERROR_CODE
)
}
private fun handleHttpExceptions(throwable: HttpException): Resource.Error {
return when (throwable.code()) {
502 -> createDefaultResponseError(stringResourceProvider.getString(R.string.bad_gateway_message))
500 -> createDefaultResponseError(stringResourceProvider.getString(R.string.internal_server_error))
404 -> createDefaultResponseError(stringResourceProvider.getString(R.string.url_not_responding))
else -> {
createUnexpectedError(throwable)
}
}
}
private fun createUnexpectedError(throwable: Throwable) : Resource.Error =
Resource.Error(
throwable.message ?: stringResourceProvider.getString(R.string.unexpected_error),
DEFAULT_ERROR_CODE
)
private fun createDefaultResponseError(
userMessage: String
): Resource.Error {
return Resource.Error(
userMessage,
DEFAULT_ERROR_CODE
)
}
companion object {
private const val DEFAULT_ERROR_CODE = -1
}
}