Bulletproof Error Handling in Kotlin Multiplatform with ResponseResult and safeRequest
Wrap every network call at the boundary, classify outcomes, and return a structured ResponseResult so callers receive consistent, actionable results.
重點摘要
ResponseResult sealed type: Success, Error, Empty for all network calls
safeRequest wraps HttpClient requests and funnels responses/exceptions to handlers
handleResponse and handleException map HTTP codes and Ktor exceptions to typed ErrorType values
This article presents a consistent networking contract for Kotlin Multiplatform: every repository call returns a ResponseResult<T> — either Success, Error, or Empty. ResponseResult provides an ErrorType enum (NETWORK, SERVER, CLIENT, SERIALIZATION, TIMEOUT, UNAUTHORIZED, etc.), transformation operators (map, flatMap, fold) and helpers to keep repositories simple. The HttpClient extension safeRequest executes requests and delegates to handleResponse (which maps HTTP status codes, extracts server messages via a DefaultResponseDto envelope, and treats special codes like 402/424/429) or handleException (which classifies serialization, network, timeout, and HTTP exceptions). All error paths log technical details via logAndReturnError while returning user-facing messages. The result is three-line repository methods, predictable UI branching on ErrorType, and cleaner testing; the next part covers ViewModel RequestState and UI integration.
在 Kotlin Multiplatform 中使用 ResponseResult 与 safeRequest 实现稳健的错误处理
在边界处包裹每次网络请求、分类结果并返回结构化的 ResponseResult,使调用方始终得到一致且可操作的响应。
重點摘要
统一返回类型 ResponseResult(Success / Error / Empty),简化上层处理
safeRequest 封装 HttpClient,请求由 handleResponse 或 handleException 统一处理
将 HTTP 状态码与异常映射到 ErrorType,记录技术日志并提供用户友好讯息
本文描述了一套在数据层统一网络错误处理的方案:所有仓库函数返回 ResponseResult<T>(Success、Error 或 Empty),并以 ErrorType(如 NETWORK、SERVER、SERIALIZATION、TIMEOUT、UNAUTHORIZED 等)区分错误类型。通过 safeRequest 执行请求,handleResponse 根据状态码(包含 401、402、424、429 等特殊码并读取 Retry-After)解析响应并尝试提取服务器消息,handleException 分类序列化失败、网络失败、超时与 HTTP 级异常。所有错误路径统一由 logAndReturnError 记录详细技术信息并返回面向用户的消息,结果是仓库实现极简、UI 可依据 ErrorType 做明确处理,且更便于测试。
在 Kotlin Multiplatform 中用 ResponseResult 與 safeRequest 建立強固的錯誤處理
在邊界處包裝每次網路呼叫、分類結果,並回傳結構化的 ResponseResult,讓呼叫端始終收到一致可操作的回應。
重點摘要
以 ResponseResult(Success / Error / Empty)統一所有網路回傳類型
safeRequest 擴充 HttpClient,將回應與例外集中處理
根據狀態碼與例外對應 ErrorType,並將技術細節寫入日誌、用戶顯示友善訊息
本文提出一個在資料層統一錯誤處理的做法:所有 repository 的網路呼叫都回傳 ResponseResult<T>(Success、Error 或 Empty),搭配 ErrorType 列舉(如 NETWORK、SERVER、SERIALIZATION、TIMEOUT、UNAUTHORIZED 等)讓 UI 能依類型分支。safeRequest 封裝 HttpClient 請求,handleResponse 根據 HTTP 狀態碼(含 401、402、424、429 等例外映射)解析回傳並嘗試擷取伺服器訊息,handleException 則分類 Ktor 可能拋出的序列化、網路、逾時或 HTTP 例外。所有路徑以 logAndReturnError 記錄技術細節並回傳使用者可見的錯誤訊息,使 repository 簡潔且易測試。下一篇將介紹 ViewModel 的 RequestState 與 UI 整合。