ネットワークとパースのエラーを捕捉する
Ktorとserializerの例外を結果に変換します
「ネットワークとパースのエラーを捕捉する」はCoddyKit上の無料Kotlin Multiplatform Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはKotlin Multiplatform Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Kotlin Multiplatform Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🛡️
よくある質問
「ネットワークとパースのエラーを捕捉する」レッスンは無料ですか?
はい。「ネットワークとパースのエラーを捕捉する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Kotlin Multiplatform Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Kotlin Multiplatform Academyコースには全4レッスンが含まれています。
「ネットワークとパースのエラーを捕捉する」で何を学びますか?
Ktorとserializerの例外を結果に変換します ブラウザで直接実行するハンズオンコードでKotlin Multiplatform Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Kotlin Multiplatform Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのKotlin Multiplatform Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「ネットワークとパースのエラーを捕捉する」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このKotlin Multiplatform Academyレッスンでコードを書いて実行できますか?
はい。すべてのKotlin Multiplatform Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Sealed Result Type
- ネットワークとパースのエラーを捕捉する
- エラーをUIメッセージにマッピングする
- RetryとOffline Fallbacks