1+ package com.enginebai.base.utils
2+
3+ import android.app.Application
4+ import com.enginebai.base.R
5+ import io.reactivex.exceptions.OnErrorNotImplementedException
6+ import io.reactivex.exceptions.UndeliverableException
7+ import io.reactivex.functions.Consumer
8+ import io.reactivex.plugins.RxJavaPlugins
9+ import io.reactivex.subjects.PublishSubject
10+ import retrofit2.HttpException
11+ import timber.log.Timber
12+ import java.net.ConnectException
13+ import java.net.SocketException
14+ import java.net.SocketTimeoutException
15+ import java.net.UnknownHostException
16+
17+ class RxErrorHandler (private val application : Application ) : Consumer<Throwable> {
18+
19+ val errorMessageToDisplay = PublishSubject .create<String >()
20+
21+ init {
22+ RxJavaPlugins .setErrorHandler(this )
23+ }
24+
25+ override fun accept (t : Throwable ) {
26+ when (val cause = parseCause(t)) {
27+ is SocketTimeoutException , is ConnectException , is UnknownHostException , is SocketException -> {
28+ Timber .w(" Network fail: $cause " )
29+ errorMessageToDisplay.onNext(application.getString(R .string.error_network_fail))
30+ }
31+ is HttpException -> {
32+ val url = cause.response()?.raw()?.request?.url
33+ errorMessageToDisplay.onNext(" HTTP ${cause.code()} of $url " )
34+ }
35+ else -> {
36+ Timber .e(cause)
37+ throw cause
38+ }
39+ }
40+ }
41+
42+ private fun parseCause (t : Throwable ): Throwable {
43+ when (t) {
44+ is OnErrorNotImplementedException , is UndeliverableException , is RuntimeException -> {
45+ t.cause?.run { return this } ? : throw ParseCauseFailException (t)
46+ }
47+ }
48+ return t
49+ }
50+ }
51+
52+ class ParseCauseFailException (t : Throwable ) : RuntimeException(t)
0 commit comments