0

I have trying to parse actual response body even if server returns 401 HTTP Exception.

protected inline fun <RESPONSE : ParentResponse> executeNetworkCall(
        crossinline request: () -> Single<RESPONSE>,
        crossinline successful: (t: RESPONSE) -> Unit,
        crossinline error: (t: RESPONSE) -> Unit) {

    request().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    { t: RESPONSE ->
                        errorHandler!!.checkApiResponseError(t)?.let {
                            listener?.onErrorWithId(t.message!!)
                            error(t)
                            return@subscribe
                        }
                        successful(t)
                    }
                    ,
                    { t: Throwable ->
                        listener?.onErrorWithId(t.message!!)
                    }
            )
}

This is what I have written. It parses response and error very well when both are separate in usual ways. But I want to parse success response when I get even 401 HTTP Exception.

Thanks in advance..

Response with 401 HTTP looks like below.

401 Unauthorized - HTTP Exception 
{"Message":"Authentication unsuccessful","otherData":"//Some data"}

By the way I have to check HTTP error code..

if (statusCode==401){
 print("Authentication unsuccessful")
}
Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38

1 Answers1

1

You can use Retrofit's Response class for that purpose, which is a wrapper over your response object, it has both your response's data and error bodies and also the success state, so instead of doing Single<RESPONSE> use Single<Response<RESPONSE>>.

Parsing the response object can be something like this:

{ t: Response<RESPONSE> ->
if (t.isSuccessful())
    // That's the usual success scenario
else
    // You have a response that has an error body.
}
,
{ t: Throwable ->
    // You didn't reach the endpoint somehow, maybe a timeout or an invalid URL.
}
Ahmed Ashraf
  • 2,795
  • 16
  • 25