RXJava改造用户的API错误 [英] Rxjava retrofit parse api error for user

查看:66
本文介绍了RXJava改造用户的API错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在图书馆项目中使用带有翻新功能的RxJava.一切都很好,当我请求数据时我得到了预期的结果.

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>

来自API类:

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")
                    })

一切正常,但是如果发生API错误,则API向我们发送例如:

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"}

我想要的是将这个错误显式地提供给发生此错误的前端,因为直到现在,当我从Observable错误中得到该错误时,前端仍无法解析我要构建的该错误.因此,我的目的是从库中解析此错误,使用提供的API json构建Error POJO,并在前端收到错误时将其发送.如果错误不是由API引起的,那么前端应该会得到正常的错误.

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.

推荐答案

您将需要 retrofit 实例,以将异常映射到错误响应.这是一个示例:

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")
            }
        })

这篇关于RXJava改造用户的API错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆