Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fuel get the body response on error

Tags:

android

kotlin

How can I achieve this? This is the request im doing.

Fuel.get(url)
    .timeout(TIMEOUT)
    .body(myRequest.parameters!!, Charsets.UTF_8)
    .responseString() { _, response, result ->
                Log.e("result", "$result")
                when (result) {
                    is Result.Success -> {
                        completionHandler(result.get(), null)
                    }
                    is Result.Failure -> {
                        Log.e("fail", "${response}")
                        completionHandler(null, Error(response.responseMessage))
                    }
                }
            }

And the response im getting is:

Response : Bad Request
Length : 122
Body : ({"message":"You have already booked that iceCream"})
Headers : (9)
Connection : [keep-alive]
Content-Length : [122]
Content-Type : [application/json; charset=utf-8]
Date : [Thu, 03 May 2018 07:33:21 GMT]
Server : [nginx/1.12.1]

I want to return the body message as my error.

like image 878
Mikael Quick Avatar asked May 03 '18 07:05

Mikael Quick


3 Answers

As it is mentioned in this issue. You can receive the body with response.data, which returns ByteArray. Therefore the code could look something like this:

val myBody = String(response.data)

Another solution would be, disabling the HTTP Code validator, which can be achieved with: FuelManager.removeAllResponseInterceptors()

like image 64
Samuel Kodytek Avatar answered Nov 10 '22 18:11

Samuel Kodytek


if your code uses awaitByteArrayResponse and got Result<?, FuelError>> or FuelError object, try this: val (content, error) = result // Result<?, FuelError>> val strContent = error.errorData.toString(Charsets.UTF_8)

like image 3
tateisu Avatar answered Nov 10 '22 19:11

tateisu


Anyhow I solved It substringing the message out. But Fuel is a big respected library so there is probally another more goodlooking way. But it's working :)

like image 1
Mikael Quick Avatar answered Nov 10 '22 19:11

Mikael Quick