classRxErrorHandlingCallAdapterFactory:CallAdapter.Factory(){overridefunget(returnType:Type,annotations:Array<Annotation>,retrofit:Retrofit):CallAdapter<*,*>?{if(getRawType(returnType)!=Observable::class.java){returnnull// Ignore non-Observable types.}//获取代理valdelegate=retrofit.nextCallAdapter(this,returnType,annotations)asCallAdapter<Any?,Observable<Any?>>returnobject:CallAdapter<Any?,Any?>{overridefunadapt(call:Call<Any?>):Any{// Delegate to get the normal Observable...valobservable=delegate.adapt(call)// ...and change it to send notifications to the observer on the specified scheduler.returnobservable.onErrorResumeNext(Function<Throwable,ObservableSource<Any?>>{t->if(tisApiError){Observable.error<Any>(t)}elseObservable.error<Any>(asRetrofitException(t))}).observeOn(AndroidSchedulers.mainThread())}overridefunresponseType():Type{returndelegate.responseType()}}}privatefunasRetrofitException(throwable:Throwable):RetrofitException{try{when(throwable){isHttpException->{valresponse=throwable.response()returnRetrofitException.httpError(response.raw().request().url().toString(),response)}isIOException->{returnRetrofitException.networkError(throwable)}isUnknownHostException->{returnRetrofitException.networkError(throwable)}}}catch(e:Exception){returnRetrofitException.unexpectedError(e)}returnRetrofitException.unexpectedError(throwable)}}
publicclassRetrofitExceptionextendsRuntimeException{publicstaticRetrofitExceptionhttpError(Stringurl,Responseresponse){Stringmessage=response.code()+" "+response.message();returnnewRetrofitException(message,url,response,Kind.HTTP,null);}publicstaticRetrofitExceptionnetworkError(IOExceptionexception){Stringmessage=MyApp.getAppContext().getResources().getString(R.string.network_error);exception.printStackTrace();returnnewRetrofitException(message,null,null,Kind.NETWORK,exception);}publicstaticRetrofitExceptionunexpectedError(Throwableexception){Stringmessage=MyApp.getAppContext().getResources().getString(R.string.unexpected_error);exception.printStackTrace();returnnewRetrofitException(message,null,null,Kind.UNEXPECTED,exception);}privatefinalStringurl;privatefinalResponseresponse;privatefinalKindkind;publicRetrofitException(Stringmessage,Stringurl,Responseresponse,Kindkind,Throwableexception){super(message,exception);this.url=url;this.response=response;this.kind=kind;}/** The request URL which produced the error. */publicStringgetUrl(){returnurl;}/** Response object containing status code, item_data, body, etc. */publicResponsegetResponse(){returnresponse;}/** The event kind which triggered this error. */publicKindgetKind(){returnkind;}}