https://kotlinlang.org logo
#ktor
Title
# ktor
c

cafonsomota

06/21/2022, 11:41 AM
hello all! I’ve just updated Ktor 2.0.0-beta-1 to 2.0.2 (client), and I’ve noticed something strange happening: • When a request fails (for instance, receiving a 403), I get the deserialized object as null instead of an exception For example:
Copy code
public suspend fun someCall(random: RandomObject): SomeObject = <http://client.post|client.post>(URL) {
  setBody(random)
}.body()
Previously, when I called this from:
Copy code
public suspend fun invokeSomeCall(random: RandomObject, onSuccess: (SomeObject) -> Unit, onFailure: (SomeErrorObject) -> Unit) {
  try {
    val response = EntityManagerAPI.someCall(random)

    coroutineScope {
      onSuccess(response)
    }
  } catch (e: Exception) {
    coroutineScope {
      onFailure(processException(e))
    }
  }
}
And the server returns a 403, the deserialization of
SomeObject
would fail, and I’ll call
onFailure
. Now, with the new version,
onSuccess
is called and it’s deserialized with all the default values. The rules that I’m using for
Json
on
ContentNegotation
are:
Copy code
public val nonStrictJson: Json = Json {
  prettyPrint = true
  isLenient = true
  ignoreUnknownKeys = true
}
From my tests if I change
isLenient
to false, I get the previous behaviour; in any case I’m trying to understand what changed, or what I might be doing wrong? Is there a better approach here? Perhaps, checking the status code before?
h

Helio

06/21/2022, 11:48 AM
I’m not 100% if that’s the reason for your problem. But during the migration of the some of my services I experienced similar behaviour. The solution on my case was configuring the HttpClient with
expectSuccess = true
.
c

cafonsomota

06/21/2022, 11:52 AM
Wow! I wasn’t aware of this:
Copy code
/**
 * Terminate [HttpClient.receivePipeline] if status code is not successful (>=300).
 */
public var expectSuccess: Boolean = false
🙂 1
It worked! I wasn’t aware of this change:
https://github.com/ktorio/ktor/pull/2783
I wonder how many people will get their apps broken 😅. @Helio was there some guideline that I might have missed during the migration?
I looked through this guide and there blogpost. https://blog.jetbrains.com/ktor/2022/04/11/ktor-2-0-released/
c

cafonsomota

06/21/2022, 12:00 PM
Thank you!! I understood what I did wrong, I was using 2.0.0-beta1 that didn’t had the change, but it seems when 2.0.0 was released the default value has changed; it seems I was too early adopter 🙂
h

Helio

06/21/2022, 12:08 PM
Glad it worked. =)
3 Views