问题
What is the approach to wrapping responses from the server and then process? The API is returning responses in the following format:
SUCCESS:
{
"data": [],
"statusCode": 200,
"statusMessage": "Operation success",
"success": true
}
FAILURE:
{
"errors": [],
"statusCode": 500,
"statusMessage": "Something went wrong",
"success": false
}
I'm trying to apply Clean Architecture principles to my application and I want to know how can I wrap the responses to better handle errors?
回答1:
- fillCities() calls getCities()
- getCities() calls getCityList()
getCities processes the response that comes from getCityList endpoint through funcErrorCheckAndTransform and returns back an observable to presenter layer
fun <T> funcErrorCheckAndTransform(): (BaseResponse<T>) -> Observable<T> { return { response -> if (response.isSuccess) { Observable.just(response.data) } else { val e = Exception(response.errorMsg) Timber.e(e) Observable.error(e) } } } override fun getCities(): Observable<out Cities> { return locationService.getCityList() .subscribeOn(schedulerProvider.io()) .flatMap(funcErrorCheckAndTransform()) .observeOn(schedulerProvider.ui()) } @GET("getcitylist") fun getCityList(): Observable<BaseResponse<ProfileResponse.Cities>> override fun fillCities(defaultCityName: String?) { view.showProgress(R.string.cities_are_getting_dialog_message) compositeDisposable.add( interactor.getCities().subscribe( { view.hideProgress() view.fetchCities(it, defaultCityName) }, { error -> view.onError(error) } )) }
来源:https://stackoverflow.com/questions/51608002/how-to-wrap-api-responses-to-handle-success-and-error-based-on-clean-architectur