Clean Error Handling in Android with runCatching, MVI, and Flow
Error handling in Android is not just about catching exceptions — it’s about keeping ViewModels alive, maintaining a predictable UI, and preserving business logic.
重點摘要
Use runCatching to encapsulate and map exceptions without breaking control flow
Integrate error states into MVI so UI remains predictable and recoverable
Leverage Kotlin Flow to propagate results and errors while keeping ViewModels alive
This article examines a disciplined approach to error handling in Android that goes beyond merely catching exceptions. It argues for combining Kotlin's runCatching, the MVI (Model-View-Intent) pattern, and Flow to keep ViewModels running, ensure UI predictability, and protect business logic from being disrupted by failures. Rather than letting exceptions crash components or scatter error-handling code, the piece advocates encapsulating outcomes, modeling error states within the UI state, and using reactive streams to deliver results and failures in a controlled way. The result is more robust apps where errors are surfaced, handled, and rendered consistently, enabling safer retries, clearer user feedback, and cleaner separation of concerns between presentation and domain layers.
在 Android 中用 runCatching、MVI 和 Flow 实现干净的错误处理
错误处理不仅仅是捕获异常,而是要让 ViewModel 存活、保持 UI 可预测,并保护业务逻辑不被中断。
重點摘要
使用 runCatching 封装执行结果,避免中断控制流
将错误状态纳入 MVI 的 UI state,确保界面行为可预测
通过 Flow 传播结果与错误,防止 ViewModel 因异常终止
本文探讨在 Android 中更稳健的错误处理思路,主张结合 Kotlin 的 runCatching、MVI 架构与 Flow,既不只是捕获异常,也要维持 ViewModel 的生命周期、让 UI 表现一致并保护业务逻辑。通过封装返回值与异常、在状态中显式建模错误,并以 Flow 作为结果与错误的传输通道,可以使错误被可控地呈现与处理,从而实现更清晰的一致性、便于重试与更好的用户反馈,同时保持表示层与领域层的职责分离。
在 Android 中以 runCatching、MVI 與 Flow 實現乾淨的錯誤處理
錯誤處理不僅是捕捉例外,而是要讓 ViewModel 持續存活、讓 UI 可預期,並保護業務邏輯不被中斷。
重點摘要
以 runCatching 包裝執行結果,避免破壞流程控制
將錯誤狀態納入 MVI 的 UI state,維持可預測的介面行為
透過 Flow 傳遞結果與錯誤,確保 ViewModel 不會因例外終止
本文討論在 Android 中更乾淨且可維護的錯誤處理策略,強調不只是在程式中捕捉例外,而是要透過 runCatching 封裝執行結果、在 MVI 架構中明確表示錯誤狀態,並利用 Kotlin Flow 以反應式方式傳遞 success 或 failure。這種做法能讓 ViewModel 保持存活、UI 行為可預期,並將錯誤處理與業務邏輯分離,使重試、使用者回饋與狀態轉換更一致且易於測試與維護。