0Pricing
Kotlin Multiplatform Academy · Lección

Capture errores de red y análisis

Convierta las excepciones de Ktor y del serializer en resultados

Capture errores de red y análisis es una lección gratuita de Kotlin Multiplatform Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Kotlin Multiplatform Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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. 🛡️

Preguntas frecuentes

¿La lección «Capture errores de red y análisis» es gratis?

Sí — el texto completo de «Capture errores de red y análisis» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Kotlin Multiplatform Academy, actualiza a CoddyKit PRO. El curso de Kotlin Multiplatform Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Capture errores de red y análisis»?

Convierta las excepciones de Ktor y del serializer en resultados Practicas Kotlin Multiplatform Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Kotlin Multiplatform Academy?

No se requiere experiencia previa. Kotlin Multiplatform Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Capture errores de red y análisis»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Kotlin Multiplatform Academy?

Sí. Cada lección de Kotlin Multiplatform Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Un tipo de resultado sealed
  2. Capture errores de red y análisis
  3. Convierta los errores en mensajes de interfaz
  4. Reintentos y alternativas sin conexión
← Volver a Kotlin Multiplatform Academy