Retrofit / RxJava - 获取http响应代码

时间:2017-09-19 06:41:33

标签: android retrofit2 rx-java2 http-error

Android,Retrofit,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的错误代码: enter image description here

2 个答案:

答案 0 :(得分:3)

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了解更多信息。

答案 1 :(得分:3)

只需使用cast ??

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();
                });