0Pricing
Kotlin Multiplatform Academy · Lezione

Gestire errori di rete e parsing

Convertire le eccezioni di Ktor e del serializer in risultati

Gestire errori di rete e parsing è una lezione Kotlin Multiplatform Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Kotlin Multiplatform Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Kotlin Multiplatform Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Where Errors Begin

Most failures appear at two spots: the network call and the JSON parse. Catching them here keeps the rest of your shared code clean and calm.

Wrap the Risky Call

Put the Ktor request and the decode inside a single try block. One guarded spot is easier to reason about than scattered checks.

try {
  val user = client.get(url).body<User>()
} catch (e: Exception) { }

Catch Network Failures

A dropped connection throws an IOException. Catch it and turn it into a clear Failure your UI can present as a connectivity problem.

catch (e: IOException) {
  Failure("No connection")
}

Catch Parsing Failures

When JSON does not match your model, kotlinx.serialization throws a SerializationException. Catch it separately so you know data, not the network, was bad.

catch (e: SerializationException) {
  Failure("Bad data")
}

Order Your catch Blocks

List the specific exceptions first and a broad Exception last. Kotlin matches top to bottom, so narrow types must come before the catch-all.

Return, Do Not Rethrow

Inside each catch, build a Failure and return it. Rethrowing would just push the crash up to the apps you are trying to protect.

Keep It in commonMain

This guarding belongs in shared code, right around the call. Both Android and iOS then receive the same safe Result with no extra work.

Inspect Ktor Status Codes

A reachable server can still answer 404 or 500. Check the response status and map non-2xx codes to a Failure too.

if (!resp.status.isSuccess())
  return Failure("Server error")

Avoid Swallowing Silently

Never leave an empty catch. Log the cause before returning Failure so you can still debug what really happened on a device.

runCatching as a Shortcut

Kotlin offers runCatching to wrap a block into a Result-like value, a tidy alternative when you do not need custom catch logic.

val r = runCatching { fetch() }

One Funnel, Two Sources

Network and parsing errors now flow through one funnel into your Failure type, so callers handle both with the same simple branch.

Quick Check

Think about how kotlinx.serialization signals trouble.

Recap

You wrapped the call in try, caught IOException and SerializationException separately, mapped bad status codes, and returned tidy Failures from shared code. 🛡️

Domande Frequenti

La lezione «Gestire errori di rete e parsing» è gratuita?

Sì — il testo completo di «Gestire errori di rete e parsing» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Kotlin Multiplatform Academy, passa a CoddyKit PRO. Il corso Kotlin Multiplatform Academy include 4 lezioni in totale.

Cosa imparerò in «Gestire errori di rete e parsing»?

Convertire le eccezioni di Ktor e del serializer in risultati Eserciti Kotlin Multiplatform Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Kotlin Multiplatform Academy?

Non è richiesta alcuna esperienza precedente. Kotlin Multiplatform Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Gestire errori di rete e parsing»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Kotlin Multiplatform Academy?

Sì. Ogni lezione Kotlin Multiplatform Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Un tipo Result sealed
  2. Gestire errori di rete e parsing
  3. Mappare gli errori sui messaggi dell'interfaccia
  4. Retry e fallback offline
← Torna a Kotlin Multiplatform Academy