Created
August 21, 2018 15:25
-
-
Save KravaDanil/fd35e1da65b863cadb190af316e80a51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ResponseMapper<T> : RMapper<T> { | |
| private var errorString: String = "{}" | |
| override fun getErrorString() = errorString | |
| override fun apply(it: Response<T>): Single<T> { | |
| return when { | |
| it.isSuccessful -> Single.just(it.body()!!) | |
| it.errorBody() == null -> Single.error<T>(UnrecoverableException("Unknown exception")) | |
| else -> { | |
| if (it.errorBody()!!.byteStream().available() > 0) { | |
| errorString = it.errorBody()!!.string() | |
| } | |
| val json = JSONObject(getErrorString()) | |
| val str = if (json.has("errors") && json.getJSONArray("errors").length() > 0 && | |
| (json.getJSONArray("errors").get(0) as JSONObject).length() > 0 && | |
| (json.getJSONArray("errors").get(0) as JSONObject).keys().hasNext()) { | |
| val errorsObj = json.getJSONArray("errors").get(0) as JSONObject | |
| errorsObj.keys() | |
| .asSequence() | |
| .map { errorsObj.getString(it) } | |
| .joinToString("\n") | |
| } else if (json.has("error_description")) { | |
| json.getString("error_description") | |
| } else if (json.has("message")) { | |
| json.getString("message") | |
| } else { | |
| errorString | |
| } | |
| when (it.code()) { | |
| 400 -> Single.error<T>(BadRequestException(str)) | |
| 401 -> Single.error<T>(UnauthorizedException(str)) | |
| 502, 503, 504 -> Single.error<T>(InternalServerException(str)) | |
| else -> Single.error<T>(UnrecoverableException(str)) | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment