Skip to content

Instantly share code, notes, and snippets.

@tieorange
Created April 10, 2019 08:04
Show Gist options
  • Save tieorange/86e27921e1dc94caa285fd6c650ac2dd to your computer and use it in GitHub Desktop.
Save tieorange/86e27921e1dc94caa285fd6c650ac2dd to your computer and use it in GitHub Desktop.
open class ErrorHandler(
private val errorDisplay: ErrorDisplay,
private val logger: Logger,
private val navigation: Navigation,
private val signOutUserUseCase: SignOutUserUseCase
) {
open fun handleError(tag: String, error: Throwable, retryAction: ((View) -> Unit)? = null) {
logger.logError(tag, error)
val decomposedError = getDecomposedErrorType(error)
when (decomposedError) {
is HttpException -> httpException(decomposedError)
is UnknownHostException ->
noInternet(decomposedError)
is CannotModifyRemoteContentException ->
errorDisplay.displayError(
decomposedError.message.orEmpty(),
codeOfCannotReportContentException(decomposedError),
retryAction
)
is AddingToReadingListFailedException ->
errorDisplay.displayError(
decomposedError.message.orEmpty(),
codeOfCannotReportContentException(decomposedError),
retryAction
)
else ->
generalError(decomposedError)
}
}
private fun httpException(exception: HttpException) {
if (shouldSignOutAndGoToJoinScreen(exception)) signOutAndGoToJoinScreen()
else displayHttpExceptionError(exception)
}
private fun signOutAndGoToJoinScreen() {
signOutUserUseCase.perform()
.subscribe { navigation.joinScreen(false).start() }
}
protected open fun shouldSignOutAndGoToJoinScreen(exception: HttpException)
= (exception.code() == UNAUTHORIZED)
protected fun displayHttpExceptionError(decomposedError: HttpException) {
errorDisplay.displayError(
decomposedError.code().toString() + ": " + decomposedError.message(),
decomposedError.code()
)
}
protected fun getDecomposedErrorType(error: Throwable) =
(error as? CompositeException)?.exceptions?.firstOrNull() ?: error
private fun generalError(error: Throwable) {
errorDisplay.displayError(error.message ?: error.toString())
}
private fun noInternet(error: Throwable) {
errorDisplay.displayError(error.message.orEmpty(), NO_INTERNET)
}
private fun codeOfCannotReportContentException(error: AddingToReadingListFailedException) =
mapUnprocessableError(error.cause, ALREADY_ADDED)
private fun codeOfCannotReportContentException(error: CannotModifyRemoteContentException) =
mapUnprocessableError(error.cause, HTTP_ERROR_UNPROCESSABLE)
private fun mapUnprocessableError(cause: Throwable?, unprocessableCode: Int) =
if (cause is HttpException && cause.code() == HTTP_ERROR_UNPROCESSABLE) unprocessableCode
else CANNOT_MODIFY_REMOTE_CONTENT
companion object {
const val UNKNOWN_CODE = -1
const val UNAUTHORIZED = 401
const val HTTP_ERROR_UNPROCESSABLE = 422
const val NO_INTERNET = 1000
const val CANNOT_MODIFY_REMOTE_CONTENT = 1001
const val ALREADY_ADDED = 1002
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment