How to wrap API responses to handle success and error based on Clean Architecture?

十年热恋 提交于 2021-01-28 12:48:51

问题


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:


  1. fillCities() calls getCities()
  2. getCities() calls getCityList()
  3. 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

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