How do I get Response body when there is an error when using Retrofit 2.0 Observables

冷暖自知 提交于 2019-12-02 17:59:51
Tim C

Just check if the throwable is an instance of HttpException and then you can access the retrofit response

if (e instanceof HttpException) {
    ResponseBody body = ((HttpException) e).response().errorBody();
    ...
}

Then you can use the converter to deserialize it (or do it yourself).

You can add this code block to display the error message.

@Override
public void onFailure(Throwable t) {

 if (t instanceof HttpException) {
        ResponseBody body = ((HttpException) t).response().errorBody();
        Gson gson = new Gson();
        TypeAdapter<ErrorParser> adapter = gson.getAdapter
                (ErrorParser
                        .class);
        try {
            ErrorParser errorParser =
                    adapter.fromJson(body.string());

            Logger.i(TAG, "Error:" + errorParser.getError());

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