Rxjava retrofit parse api error for user

拥有回忆 提交于 2019-12-13 03:54:24

问题


I'm using RxJava with retrofit in a library project. Everything is working fine, I get the expected result when I request data.

@GET(Routes.ME)
fun getUserObservable(): Observable<User>

From the API class:

fun getUser(): Observable<User> {
    return usersService.getUserObservable()
}

From the main project which use this library, I get the user like this:

api.getUser().observeOn(AndroidSchedulers.mainThread())
             .subscribeOn(Schedulers.io())
             .subscribe({ user ->
                        println("Get user success : $user")
                    }, { error ->
                        println("Get user error : $error")
                    })

All is working fine, but if an API error occurs, then the API send us for example:

{reason: "the reason of the error", details: "some details", type:"the type error"}

What I want is to provide explicitly this error to the front which get this error, because until now, when I get the error from the error Observable, the front can't parse this error I want to build. So my purpose is to parse this error from my library, build an Error POJO with the provided API json, and send it when the front get the error. If the error doesn't come from the API, then the front should get the normal error.


回答1:


You will need instance of retrofit to map exception to error response. Here is an example:

class Error(
        var reason: String = "",
        var details: String = "",
        var type: String = ""
)

api.getUser()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({ user ->
            println("Get user success : $user")
        }, { throwable ->
            if (throwable is HttpException) {
                val converter: Converter<ResponseBody, Error> = retrofit.responseBodyConverter(Error::class.java, emptyArray())
                val error = converter.convert(throwable.response().errorBody())
                println("Get user error : ${error.reason}")
            } else {
                println("Get user error : $throwable")
            }
        })


来源:https://stackoverflow.com/questions/46295237/rxjava-retrofit-parse-api-error-for-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!