【问题标题】:Retrofit/RxJava - get http response codeRetrofit/RxJava - 获取 http 响应代码
【发布时间】:2018-02-27 20:00:40
【问题描述】:

Android、改造、RxJava。请看这个示例调用:

 mcityService.signOut(signOutRequest)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp ->
                {
                    busyIndicator.dismiss();
                    finish();
                }, throwable ->
                {
                    Log.d(tag, throwable.toString());
                    busyIndicator.dismiss();
                    Toast.makeText(this,throwable.getMessage(),Toast.LENGTH_LONG).show();
                    finish();
                });

有人知道如何从 throwable 中获取错误代码(作为错误编号)吗?我能够获得完整的堆栈跟踪或消息(如上所示)。如何捕获错误代码?

来自 throwable 的错误代码:

【问题讨论】:

  • 请看我的调试截图。有code 字段,但无法访问
  • 除了答案之外,请检查 jake @ github.com/square/retrofit/issues/1218 的评论,这意味着任何非 200 错误都可以在 onNext 中使用 `Observable>` 或 Observable<Result<Type>>

标签: android retrofit2 rx-java2 http-error


【解决方案1】:

Retrofit 2 + Rxjava handling error这是你的答案

                @Override
            public void onError(Throwable e) {
                if (e instanceof HttpException) {
                    ResponseBody body = ((HttpException) e).response().errorBody();

                    Converter<ResponseBody, Error> errorConverter =
                        application.getRetrofit().responseBodyConverter(Error.class, new Annotation[0]);
                // Convert the error body into our Error type.
                    try {
                        Error error = errorConverter.convert(body);
                        Log.i("","ERROR: " + error.message);
                        mLoginView.errorText(error.message);
                    } catch (IOException e1) {
                    e1.printStackTrace();
                    }
                 }



            static class Error{
            String message;
            }

请参阅here 了解更多信息。

【讨论】:

  • 这真的很糟糕。我想知道为什么只有错误代码不能从 throwable 中访问,就像错误消息一样。无论如何感谢您的提示
【解决方案2】:

只使用强制转换??

mcityService.signOut(signOutRequest)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resp ->
                {
                    busyIndicator.dismiss();
                    finish();
                }, throwable ->
                {
                    Log.d(tag, throwable.toString());
                    Log.d(code, ((HttpException)throwable).code());

                    busyIndicator.dismiss();
                    Toast.makeText(this,throwable.getMessage(),Toast.LENGTH_LONG).show();
                    finish();
                });

【讨论】:

  • 还需要检查throwable是否真的是HttpException的实例。例如,如果没有可用的网络,则不是,应用程序将崩溃
  • 使用你的 throwable 的 instanceOf
猜你喜欢
  • 2016-02-19
  • 2018-10-08
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
相关资源
最近更新 更多