<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by JC on Medium]]></title>
        <description><![CDATA[Stories by JC on Medium]]></description>
        <link>https://medium.com/@shidocorporation?source=rss-2288cbd3407d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HTXznqFJq99dhe7f</url>
            <title>Stories by JC on Medium</title>
            <link>https://medium.com/@shidocorporation?source=rss-2288cbd3407d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 00:44:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shidocorporation/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unified Crash Reporting in Kotlin Multiplatform: A Production-Ready Architecture]]></title>
            <link>https://medium.com/@shidocorporation/unified-crash-reporting-in-kotlin-multiplatform-a-production-ready-architecture-75419f8764d4?source=rss-2288cbd3407d------2</link>
            <guid isPermaLink="false">https://medium.com/p/75419f8764d4</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[app-modularization]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[crashlytics]]></category>
            <dc:creator><![CDATA[JC]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 13:10:39 GMT</pubDate>
            <atom:updated>2026-11-19T14:23:05.951Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to build a single, testable, multi-backend error reporting layer that works identically on Android and iOS</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2p8rQDCq-mNa_AfqaYku7w.jpeg" /></figure><h3>The Problem</h3><p>When you start building a Kotlin Multiplatform (KMP) project seriously, one of the first production concerns you hit is observability. You need crash reports. You probably have Firebase Crashlytics already set up on Android. And you likely want Datadog on the side for correlated logs and traces.</p><p>The naive approach is to call FirebaseCrashlytics.getInstance().recordException(throwable) from your business logic. That works fine in a pure Android project. In KMP, it immediately breaks: FirebaseCrashlytics is an Android-only class. It lives in androidMain, not commonMain. Your Repository, UseCase, and ViewModel code — all sitting in commonMain — can&#39;t see it.</p><p>So what do you do? You could sprinkle expect/actual declarations around it. That works, but it ties your business logic to a specific observability backend and makes testing painful.</p><p>There’s a cleaner way. This article walks through a production implementation that solves this with a Strategy pattern, a lightweight global accessor, and a set of Kotlin extension functions that make the call-site read like natural language.</p><h3>The Dependencies: GitLive Firebase for KMP</h3><p>Before the architecture, one crucial piece: Firebase has no official KMP SDK. The community-maintained <a href="https://github.com/GitLiveApp/firebase-kotlin-sdk">GitLive Firebase wrapper</a> fills that gap. It wraps the native Firebase SDKs (Android and iOS) under a common Kotlin API.</p><p>In your libs.versions.toml:</p><pre>[versions]<br>dev-gitlive-firebase-multiplatform = &quot;2.4.0&quot;<br>datadog-multiplatform = &quot;1.6.0&quot;</pre><pre>[libraries]<br>firebase-crashlytics-multiplatform = { group = &quot;dev.gitlive&quot;, name = &quot;firebase-crashlytics&quot;, version.ref = &quot;dev-gitlive-firebase-multiplatform&quot; }<br>datadog-logs-multiplatform = { group = &quot;com.datadoghq&quot;, name = &quot;dd-sdk-kotlin-multiplatform-logs&quot;, version.ref = &quot;datadog-multiplatform&quot; }<br>datadog-rum-multiplatform = { group = &quot;com.datadoghq&quot;, name = &quot;dd-sdk-kotlin-multiplatform-rum&quot;, version.ref = &quot;datadog-multiplatform&quot; }</pre><p>And in the error handling module’s build.gradle.kts:</p><pre>kotlin {<br>    sourceSets {<br>        commonMain.dependencies {<br>            api(libs.datadog.logs.multiplatform)<br>            api(libs.firebase.crashlytics.multiplatform)<br>        }<br>    }<br>}</pre><p>Notice both are exposed with api(). Downstream modules that implement CrashReportableException will reference these types directly when building attribute maps and formatting messages.</p><h3>Architecture Overview</h3><p>The design uses three classic patterns working together:</p><ol><li><strong>Strategy</strong> — CrashReporter is an interface. Firebase and Datadog are concrete strategies.</li><li><strong>Registry</strong> — ErrorReporterManagerImpl holds a Set&lt;CrashReporter&gt; keyed by target, routing reports to the right backend.</li><li><strong>Service Locator</strong> — GlobalErrorReporter is a thread-safe singleton that the entire commonMain codebase can call without caring about DI graphs.</li></ol><p>This combination gives you:</p><ul><li>Zero platform-specific code in business logic</li><li>Easy addition of a third backend (Sentry, New Relic) by adding one class</li><li>Complete replaceability in tests via NoOp implementations</li></ul><p>Here’s the full layer diagram:</p><pre>Business Logic (UseCase / Repository)<br>        │<br>        ▼<br>  throwAndReport() — Kotlin extension function<br>        │<br>        ▼<br>  GlobalErrorReporter.get() — singleton accessor<br>        │<br>        ▼<br>  ErrorReporterManagerImpl<br>     ├──► FirebaseCrashReporter  ──► dev.gitlive Firebase.crashlytics<br>     └──► DatadogCrashReporter   ──► com.datadog.kmp.log.Logger</pre><h3>Step 1: The Core Abstraction</h3><h3>CrashReportingTarget</h3><p>A simple enum that acts as the routing key:</p><pre>enum class CrashReportingTarget {<br>    CRASHLYTICS,<br>    DATADOG,<br>}</pre><p>This enum is the linchpin of the whole design. When you call report(), you pass a Set&lt;CrashReportingTarget&gt; to control which backends receive the report. Need Firebase-only for a specific error? Pass setOf(CrashReportingTarget.CRASHLYTICS). Need both? The default covers it.</p><h3>CrashReporter</h3><p>The strategy interface:</p><pre>interface CrashReporter {<br>    val target: CrashReportingTarget<br>    fun report(throwable: Throwable, attributes: Map&lt;String, String&gt;)<br>}</pre><p>Simple. Each implementation declares which target it handles and knows how to forward a Throwable with a Map&lt;String, String&gt; of contextual attributes to its backend.</p><h3>CrashReportableException</h3><p>The contract your domain exceptions must implement:</p><pre>interface CrashReportableException {<br>    val formattedExceptionMessage: String<br>    fun getAttributesMap(<br>        contextParam: String?,<br>        featureInternalCode: String?<br>    ): Map&lt;String, String&gt;<br>    fun logLocally()<br>}</pre><p>This is the bridge between your domain model and the reporting layer. getAttributesMap is where each exception type decides what contextual data it wants to attach — HTTP status codes, operation names, feature codes, user session identifiers. logLocally logs to console/Kermit before the report goes remote, ensuring you have local visibility during development.</p><h3>Step 2: The Concrete Reporters</h3><h3>FirebaseCrashReporter</h3><pre>class FirebaseCrashReporter : CrashReporter {<br>    override val target = CrashReportingTarget.CRASHLYTICS</pre><pre>    override fun report(throwable: Throwable, attributes: Map&lt;String, String&gt;) {<br>        try {<br>            val crashlytics = Firebase.crashlytics</pre><pre>            // Attach custom keys — capped at 1024 chars per Firebase docs<br>            attributes.entries.forEach { entry -&gt;<br>                val key = entry.key.take(1024)<br>                val value = entry.value.take(1024)<br>                crashlytics.setCustomKey(key, value)<br>            }</pre><pre>            crashlytics.recordException(throwable)</pre><pre>            // Clear keys after recording to prevent bleed into future crashes<br>            attributes.keys.forEach { key -&gt;<br>                crashlytics.setCustomKey(key, &quot;&quot;)<br>            }<br>        } catch (e: Exception) {<br>            // The crash reporter must never be a source of crashes itself<br>            e.printStackTrace()<br>        }<br>    }<br>}</pre><p>A few design decisions worth noting:</p><p><strong>The 1024-char cap</strong>: Firebase’s custom keys have a 1024-character limit per key and value. Silently truncating with .take(1024) is safer than letting the SDK throw.</p><p><strong>Key cleanup after recording</strong>: This is subtle but important. Firebase’s custom keys are <em>persistent</em> — they survive across crash reports. If you set feature_code = &quot;DATA&quot; for one error and don&#39;t clear it, the next unrelated crash will carry that key. The cleanup loop prevents this contamination.</p><p><strong>The outer try/catch</strong>: The reporter wraps the entire body. If Firebase isn’t initialized yet, or if the gitlive wrapper has a bug, your app should not crash because of crash reporting. It’s a safety net.</p><h3>DatadogCrashReporter</h3><pre>class DatadogCrashReporter : CrashReporter {<br>    override val target = CrashReportingTarget.DATADOG</pre><pre>    override fun report(throwable: Throwable, attributes: Map&lt;String, String&gt;) {<br>        try {<br>            logErrorOnDatadog(throwable, attributes)<br>        } catch (e: Exception) {<br>            e.printStackTrace()<br>        }<br>    }<br>}</pre><p>Delegates to a shared logErrorOnDatadog function backed by a lazily initialized Datadog logger:</p><pre>internal val datadogKmpLogger by lazy {<br>    Logger.Builder()<br>        .setNetworkInfoEnabled(true)<br>        .setPrintLogsToConsole(true)<br>        .setRemoteSampleRate(100f)<br>        .setBundleWithRumEnabled(true)   // correlates logs with RUM sessions<br>        .setName(&quot;KMPBusinessLogic&quot;)<br>        .setService(&quot;your-app-kmp&quot;)<br>        .build()<br>}</pre><pre>fun logErrorOnDatadog(<br>    exception: Throwable,<br>    attributesMap: Map&lt;String, String&gt;,<br>) {<br>    val errorMessage = exception.message<br>        ?.takeIf { it.isNotBlank() }<br>        ?: &quot;Non-fatal Exception in KMP&quot;</pre><pre>    datadogKmpLogger.error(<br>        message = errorMessage,<br>        throwable = exception,<br>        attributes = attributesMap<br>    )<br>}</pre><p>The by lazy ensures the Datadog SDK is fully initialized before the logger is first built. .setBundleWithRumEnabled(true) is the key flag for correlating error logs with active RUM sessions — without it, you get logs and RUM events that have no visible connection in the Datadog dashboard.</p><h3>Step 3: The Manager and the Global Accessor</h3><h3>ErrorReporterManagerImpl</h3><pre>interface ErrorReporterManager {<br>    fun report(<br>        throwable: Throwable,<br>        attributes: Map&lt;String, String&gt;,<br>        targets: Set&lt;CrashReportingTarget&gt;,<br>    )<br>}</pre><pre>class ErrorReporterManagerImpl(<br>    private val reporters: Set&lt;CrashReporter&gt;<br>) : ErrorReporterManager {</pre><pre>    // Build a lookup map at construction time — O(1) dispatch<br>    private val reportersByTarget = reporters.associateBy { it.target }</pre><pre>    override fun report(<br>        throwable: Throwable,<br>        attributes: Map&lt;String, String&gt;,<br>        targets: Set&lt;CrashReportingTarget&gt;<br>    ) {<br>        targets.forEach { target -&gt;<br>            reportersByTarget[target]?.report(throwable, attributes)<br>        }<br>    }<br>}</pre><p>associateBy { it.target } builds the lookup Map&lt;CrashReportingTarget, CrashReporter&gt; at construction time. This means dispatching to multiple backends at call-site costs exactly N lookups in a HashMap — not a linear scan through the reporters list.</p><p>The ?.report(...) safe call is intentional: if a target was requested but no reporter is registered for it (say, you&#39;re running tests with a NoOp setup), it silently skips rather than throwing.</p><h3>GlobalErrorReporter</h3><pre>object GlobalErrorReporter {<br>    private lateinit var manager: ErrorReporterManager</pre><pre>    fun initialize(manager: ErrorReporterManager) {<br>        this.manager = manager<br>    }</pre><pre>    fun get(): ErrorReporterManager {<br>        if (!::manager.isInitialized) {<br>            throw IllegalStateException(&quot;GlobalErrorReporter not initialized&quot;)<br>        }<br>        return manager<br>    }<br>}</pre><p>This Kotlin object is the Service Locator. The design choice to throw on uninitialized access instead of returning a NoOp default is deliberate: it fails fast in development if you forgot to call initialize() at startup. A missing initialization should be loud.</p><p>In production, initialize() is called once during app startup. Anywhere in commonMain can then call GlobalErrorReporter.get().report(...) with no knowledge of which backends are configured.</p><h3>Step 4: The Ergonomic API — Kotlin Extension Functions</h3><p>This is where Kotlin really shines. Instead of forcing every call site to:</p><pre>// Verbose — the pain without extension functions<br>val attributes = exception.getAttributesMap(contextParam, featureCode)<br>exception.logLocally()<br>GlobalErrorReporter.get().report(exception, attributes, setOf(CRASHLYTICS, DATADOG))<br>throw exception</pre><p>You get two clean extension functions:</p><pre>// Reports, then throws — for cases where the exception must propagate<br>fun &lt;T&gt; T.throwAndReport(<br>    contextParam: String? = null,<br>    featureInternalCode: String? = null,<br>    targets: Set&lt;CrashReportingTarget&gt; = setOf(<br>        CrashReportingTarget.CRASHLYTICS, CrashReportingTarget.DATADOG<br>    ),<br>): Nothing where T : Throwable, T : CrashReportableException {<br>    reportToCrashReports(<br>        targets = targets,<br>        contextParam = contextParam,<br>        featureInternalCode = featureInternalCode<br>    )<br>    throw this<br>}</pre><pre>// Reports without throwing — for non-fatal, recoverable errors<br>fun &lt;T&gt; T.reportToCrashReports(<br>    contextParam: String? = null,<br>    featureInternalCode: String? = null,<br>    targets: Set&lt;CrashReportingTarget&gt; = setOf(<br>        CrashReportingTarget.CRASHLYTICS, CrashReportingTarget.DATADOG<br>    ),<br>) where T : Throwable, T : CrashReportableException {<br>    this.logLocally()<br>    val attributes = getAttributesMap(contextParam, featureInternalCode)<br>    GlobalErrorReporter.get().report(this, attributes, targets)<br>}</pre><p>The generic constraint where T : Throwable, T : CrashReportableException is the elegant part. It ensures at compile time that this extension only applies to objects that are <em>both</em> a Throwable and a CrashReportableException. You can&#39;t accidentally call it on a plain Exception or a data class.</p><p>The Nothing return type on throwAndReport tells the Kotlin compiler that this function never returns normally — it always throws. This means you can use it in else branches and exhaustive when expressions without an extra throw or return:</p><pre>// Real usage in a Repository or UseCase:<br>val result = apolloResponse.data<br>    ?: MyFeatureException(<br>        message = &quot;Data was null&quot;,<br>        featureCode = &quot;DATA_LOAD&quot;<br>    ).throwAndReport(<br>        contextParam = dataId,<br>        featureInternalCode = &quot;DATA_LOAD_NULL_DATA&quot;<br>    )</pre><h3>Step 5: Convenience Shortcuts for Single-Backend Reporting</h3><p>For cases where you know exactly which backend you need, two more extension functions provide direct access:</p><pre>// Direct Firebase Crashlytics report — skips the manager<br>fun CrashReportableException.postOnCrashlytics(<br>    contextParam: String? = null,<br>    featureInternalCode: String? = null,<br>) {<br>    val crashlytics = Firebase.crashlytics<br>    val attributes = getAttributesMap(contextParam, featureInternalCode)<br>    attributes.forEach { (key, value) -&gt;<br>        crashlytics.setCustomKey(key, value)<br>    }<br>    crashlytics.recordException(this as Throwable)<br>}</pre><pre>// Direct Datadog report — skips the manager<br>fun CrashReportableException.postOnDatadog(<br>    contextParam: String? = null,<br>    featureInternalCode: String? = null,<br>) {<br>    try {<br>        val attributes = getAttributesMap(contextParam, featureInternalCode)<br>        logErrorOnDatadog(this as Throwable, attributes)<br>    } catch (e: Exception) {<br>        e.printStackTrace()<br>    }<br>}</pre><p>These bypass the manager and global accessor entirely, talking directly to the backend SDK. Useful for initialization-time errors (before GlobalErrorReporter is initialized) or for cases where only one backend is relevant.</p><h3>Step 6: Structured Logging — The Companion System</h3><p>Crash reporting handles exceptional paths. Structured logging handles the normal observability flow: tracing operations, recording business events, flagging systemic issues.</p><p>The logging system is a parallel architecture to the crash reporter:</p><pre>@Serializable<br>data class LogContext(<br>    val severity: LogSeverity,       // TRACE, DEBUG, INFO, WARN, ERROR<br>    val fullMessage: String,<br>    val sourceSimpleClassName: String? = null,<br>    val correlationId: String? = null,<br>    val featureInternalCode: String? = null,<br>    val userSessionId: String? = null,<br>    val isSystemicEvent: Boolean = false,<br>) {<br>    fun toAttributesMap(): Map&lt;String, String&gt; = buildMap {<br>        put(&quot;facility&quot;, &quot;mobile_kmp&quot;)<br>        put(&quot;full_message&quot;, fullMessage)<br>        put(&quot;log_level&quot;, severity.name)<br>        put(&quot;is_systemic&quot;, isSystemicEvent.toString())<br>        sourceSimpleClassName?.let { put(&quot;source_class&quot;, it) }<br>        correlationId?.let { put(&quot;correlation_id&quot;, it) }<br>        featureInternalCode?.let { put(&quot;feature_code&quot;, it) }<br>        userSessionId?.let { put(&quot;user_session&quot;, it) }<br>    }<br>}</pre><p>The facility = &quot;mobile_kmp&quot; attribute is a fixed tag on every log entry. In Datadog, you can filter all KMP-originated logs by @facility:mobile_kmp and distinguish them from native Android or iOS logs.</p><p>The isSystemicEvent flag marks logs that represent system-wide issues (e.g., database corruption, full sync failure) as opposed to isolated feature errors. In Datadog dashboards, you can build a monitor specifically on systemic events.</p><h3>The Extension Function</h3><p>Any Any instance in commonMain can emit a structured log with one line:</p><pre>interface LogManager {<br>    fun log(<br>        logContext: LogContext,<br>        targets: Set&lt;LogTarget&gt; = setOf(LogTarget.DATADOG),<br>    )<br>}</pre><pre>// Extension — callable from any class<br>fun Any.logAppEvent(<br>    message: String,<br>    severity: LogSeverity = LogSeverity.INFO,<br>    correlationId: String? = null,<br>    featureInternalCode: String? = null,<br>    isSystemic: Boolean = false,<br>    userSessionId: String? = null,<br>) {<br>    val context = LogContext(<br>        severity = severity,<br>        fullMessage = message,<br>        sourceSimpleClassName = this::class.simpleName,<br>        correlationId = correlationId,<br>        featureInternalCode = featureInternalCode,<br>        isSystemicEvent = isSystemic,<br>        userSessionId = userSessionId<br>    )<br>    GlobalLogger.get().log(context)<br>}</pre><p>Usage in a UseCase:</p><pre>class SyncDataUseCase(<br>    private val repository: DataRepository<br>) {<br>    suspend operator fun invoke(userId: String) {<br>        logAppEvent(<br>            message = &quot;Starting Data sync&quot;,<br>            featureInternalCode = &quot;DATA_SYNC&quot;,<br>            correlationId = userId<br>        )<br>        // ... sync logic<br>    }<br>}</pre><p>this::class.simpleName captures &quot;SyncDataUseCase&quot; automatically and puts it in the source_class attribute — zero boilerplate for caller identification.</p><h3>Step 7: Test Doubles</h3><p>Any serious production implementation needs to be testable without hitting real SDKs. Three implementations exist for this:</p><pre>// Swallows everything silently — for performance-sensitive tests<br>class NoOpCrashReporterManager : ErrorReporterManager {<br>    override fun report(<br>        throwable: Throwable,<br>        attributes: Map&lt;String, String&gt;,<br>        targets: Set&lt;CrashReportingTarget&gt;,<br>    ) { /* intentionally empty */ }<br>}</pre><pre>// Prints to stderr — for test runs where you want visibility<br>class CrashReporterManagerForTests : ErrorReporterManager {<br>    override fun report(<br>        throwable: Throwable,<br>        attributes: Map&lt;String, String&gt;,<br>        targets: Set&lt;CrashReportingTarget&gt;,<br>    ) {<br>        throwable.printStackTrace()<br>    }<br>}</pre><pre>// A fully observable spy — for asserting that reports were sent<br>class SpyCrashReporterManager : ErrorReporterManager {<br>    val reportedThrowables = mutableListOf&lt;Throwable&gt;()<br>    val reportedAttributes = mutableListOf&lt;Map&lt;String, String&gt;&gt;()</pre><pre>    override fun report(<br>        throwable: Throwable,<br>        attributes: Map&lt;String, String&gt;,<br>        targets: Set&lt;CrashReportingTarget&gt;,<br>    ) {<br>        reportedThrowables.add(throwable)<br>        reportedAttributes.add(attributes)<br>    }<br>}</pre><p>The SpyCrashReporterManager shown above is a pattern worth adding even if it doesn&#39;t exist yet. It lets you write assertions like:</p><pre>@Test<br>fun `repository reports to crash reporter when API returns null`() = runTest {<br>    val spy = SpyCrashReporterManager()<br>    GlobalErrorReporter.initialize(spy)</pre><pre>    val repo = DataRepository(fakeDatasource)<br>    repo.loadData(userId = &quot;123&quot;)</pre><pre>    assertTrue(spy.reportedThrowables.isNotEmpty())<br>    assertEquals(<br>        &quot;DATA_NULL_RESPONSE&quot;,<br>        spy.reportedAttributes.first()[&quot;feature_code&quot;]<br>    )<br>}</pre><h3>Step 8: DI Wiring — One Function Call at Startup</h3><p>The entire system is initialized in two functions designed to be called at app startup:</p><pre>// Production — wires real Firebase and Datadog reporters<br>fun startRealCrashReporters() {<br>    val firebaseReporter = FirebaseCrashReporter()<br>    val datadogReporter = DatadogCrashReporter()<br>    val manager = ErrorReporterManagerImpl(setOf(firebaseReporter, datadogReporter))<br>    GlobalErrorReporter.initialize(manager)</pre><pre>    val logManager = LogManagerImpl(setOf(DatadogKmpLogger()))<br>    GlobalLogger.initialize(logManager)<br>}</pre><pre>// Local / Test — wires NoOp implementations<br>fun startLocalCrashReporters() {<br>    GlobalErrorReporter.initialize(NoOpCrashReporterManager())<br>    GlobalLogger.initialize(NoOpLogManager())<br>}</pre><p>On Android, call startRealCrashReporters() in your Application.onCreate() after Firebase and Datadog SDKs have been initialized. On iOS, call it from your AppDelegate or @main struct after FirebaseApp.configure() and Datadog.initialize().</p><pre>// Android — Application.kt<br>class MyApplication : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        FirebaseApp.initializeApp(this)   // native Firebase init<br>        Datadog.initialize(this, ...)      // native Datadog init<br>        startRealCrashReporters()          // KMP layer init<br>    }<br>}</pre><h3>The Full Picture: What You Get</h3><p>After wiring everything up, your domain code — sitting entirely in commonMain — can do this:</p><pre>// Scenario 1: Fatal error in a UseCase — report and throw<br>class LoadDataUseCase(private val repository: DataRepository) {<br>    suspend operator fun invoke(id: String): Data {<br>        return repository.getData(id)<br>            ?: DataNotFoundException(<br>                dataId = dataId,<br>                message = &quot;Data not found after sync&quot;<br>            ).throwAndReport(<br>                contextParam = Id,<br>                featureInternalCode = &quot;DATA_LOAD_MISSING&quot;<br>            )<br>    }<br>}</pre><pre>// Scenario 2: Non-fatal error in a Repository — report and recover<br>class DataRepositoryImpl : DataRepository {<br>    override suspend fun syncData(userId: String) {<br>        try {<br>            remoteDataSource.fetchData(userId)<br>        } catch (e: NetworkTimeoutException) {<br>            if (e is CrashReportableException) {<br>                e.reportToCrashReports(<br>                    contextParam = userId,<br>                    featureInternalCode = &quot;DATA_SYNC_TIMEOUT&quot;,<br>                    targets = setOf(CrashReportingTarget.DATADOG) // metrics only<br>                )<br>            }<br>            // Recover from local cache<br>            localDataSource.getCachedData(userId)<br>        }<br>    }<br>}</pre><p>And all of this code is:</p><ul><li><strong>Identical on Android and iOS</strong> — zero platform branches</li><li><strong>Testable</strong> — swap GlobalErrorReporter with a NoOp or Spy in tests</li><li><strong>Extensible</strong> — adding Sentry means implementing CrashReporter, adding one enum case, and updating the initialization function</li><li><strong>Observable</strong> — every report carries structured attributes that map directly to searchable fields in Firebase and Datadog</li></ul><h3>Key Takeaways</h3><p><strong>1. Strategy + Service Locator for KMP observability.</strong> The combination gives you a clean abstraction in commonMain without requiring every class to depend on a DI container.</p><p><strong>2. The key cleanup in Firebase is not optional.</strong> Firebase custom keys persist across sessions. If you don’t clear them after recordException, you&#39;ll see misleading attributes on future crashes.</p><p><strong>3. </strong><strong>Nothing return type enables idiomatic call sites.</strong> Declaring throwAndReport() as returning Nothing lets the Kotlin compiler understand the control flow, eliminating dead code warnings and enabling exhaustive when expressions.</p><p><strong>4. </strong><strong>by lazy for the Datadog logger.</strong> Datadog&#39;s SDK must be fully initialized before you build a Logger. The lazy delegate guarantees the logger is only constructed on first use — after initialization.</p><p><strong>5. </strong><strong>isSystemicEvent is a cheap but powerful triage tool.</strong> Flagging system-wide issues separately from feature-level errors lets you build focused monitors and dashboards without complex log parsing.</p><p><strong>6. Never let the reporter crash your app.</strong> Every reporter implementation wraps its body in a try/catch. Observability code is infra — it should be invisible when it fails.</p><h3>Conclusion</h3><p>Handling crash reporting in KMP requires a bit more upfront architecture than in a pure Android project, but the payoff is significant: a single error reporting path that works across platforms, is easy to test, and can route to multiple backends simultaneously.</p><p>The pattern described here — CrashReporter strategy + ErrorReporterManager registry + GlobalErrorReporter accessor + Kotlin extension functions — is production-tested and scales naturally as your observability requirements grow. Adding a third backend, changing routing logic, or introducing per-feature sampling rates are all localized changes that don&#39;t touch business logic.</p><p>The next step from here is integrating correlationId propagation across the network and database layers, so a single user action can be traced end-to-end from the KMP ViewModel through to the backend server logs. But that&#39;s an article for another day.</p><p><em>All code in this article is based on a real KMP production implementation. Names and identifiers have been generalized. The full architecture is part of a shared KMP core library consumed by Android and iOS apps.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75419f8764d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Files to an AWS Signed URL using Ktor on Android]]></title>
            <link>https://medium.com/@shidocorporation/uploading-files-to-an-aws-signed-url-using-ktor-on-android-cb9be71b20b4?source=rss-2288cbd3407d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9be71b20b4</guid>
            <category><![CDATA[upload-files-to-s3]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[JC]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 03:55:03 GMT</pubDate>
            <atom:updated>2023-10-23T04:01:13.647Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is based on a recent experience where the need arose to upload a file directly to an AWS signed URL instead of what we were previously using, GraphQL FileUpload. As there are many good examples of how to perform this upload using Retrofit 2, this post is aimed at helping other Android developers who wish to use <a href="https://ktor.io/">Ktor</a> instead of <a href="https://square.github.io/retrofit/">Retrofit</a>.</p><h3>Why Ktor?</h3><p>According to their own website: “Ktor is a framework for easily building connected applications — web applications, HTTP services, mobile and browser applications. Modern connected applications need to be asynchronous to provide the best experience to users, and Kotlin coroutines provide excellent facilities to do it in an easy and straightforward way. The goal of Ktor is to provide an end-to-end multiplatform framework for connected applications.”</p><p>Two favorable points for Ktor are:</p><ul><li>Its ease of implementation, being entirely written in Kotlin, brings a lot of convenience for those already using Kotlin on Android.</li><li>Can be used in multiplatform projects.</li></ul><p>Note: This article will not cover generating the signed URL in AWS. We will assume you already have the URL available.</p><p><strong>Adding Dependencies</strong></p><blockquote>implementation(“io.ktor:ktor-client-core:2.3.5”)<br>implementation(“io.ktor:ktor-client-android:2.3.5”)<br>implementation(“io.ktor:ktor-client-serialization:2.3.5”)<br>implementation(“io.ktor:ktor-serialization-kotlinx-json:2.3.5”)<br>implementation(“io.ktor:ktor-client-content-negotiation:2.3.5”)</blockquote><p><strong>Creating a Simple Ktor Client Object</strong></p><pre>object AppKtorClient {<br>        private const val TIMEOUT_IN_SECONDS: Long = 120<br><br>        fun getClient(): HttpClient {<br>            return HttpClient(Android) {<br>                defaultRequest {<br>                    // header(&quot;key&quot;, &quot;value&quot;)<br>                }<br><br>                install(ContentNegotiation) {<br>                    json(Json {<br>                        prettyPrint = true<br>                        isLenient = true<br>                    })<br>                }<br>            }<br>        }<br>    }</pre><p>Note the empty header; usually, when receiving the signed URL, no additional authentication is required for the request.</p><h3><strong>Uploading a File</strong></h3><p>According to the official documentation, to upload files, we could use <strong>submitFormWithBinaryData</strong>:</p><pre>suspend fun uploadFile(uploadUrl: String, file: File) {<br>    val response: HttpResponse = client.submitFormWithBinaryData(<br>        url = uploadUrl,<br>        formData = formData {<br>            append(&quot;description&quot;, &quot;Test&quot;)<br>            append(&quot;image&quot;, File(&quot;ktor_logo.png&quot;).readBytes(), Headers.build {<br>                append(HttpHeaders.ContentType, &quot;image/png&quot;)<br>                append(HttpHeaders.ContentDisposition, &quot;filename=\&quot;ktor_logo.png\&quot;&quot;)<br>            })<br>        }<br>    )<br>}</pre><p>However, internally, <strong>submitFormWithBinaryData</strong> uses the POST method to make the request, which is not accepted for AWS signed URLs, requiring the request to be made with PUT. Thus, the upload is not completed.</p><p>As an alternative, we could use the put method by passing <strong>MultiPartFormDataContent</strong> in the request body:</p><pre>suspend fun uploadFile(uploadUrl: String, file: File) {<br>    val response = client.put(uploadUrl) {<br>        body = MultiPartFormDataContent(formData {<br>            append(&quot;description&quot;, &quot;Test&quot;)<br>            this.appendInput(key = &quot;upload-image&quot;, headers = Headers.build {<br>                append(HttpHeaders.ContentLength, file.length().toString())<br>                append(HttpHeaders.ContentType, &quot;image/jpeg&quot;)<br>                append(HttpHeaders.ContentDisposition, &quot;filename=${file.name}&quot;)<br>            }, size = file.length(), block = {<br>                buildPacket {<br>                    writeFully(file.readBytes())<br>                }<br>            })<br>        })<br>    }<br>}</pre><p>We are making progress; this time the upload is completed, but the content-type appears incorrectly in the S3 bucket, coming with a value <strong>multipart/form-data; boundary = xxxxxxx</strong>.</p><p>This happens because Ktor automatically adds this content-type and the boundary, so we need to override the<strong> MultiPartFormDataContent </strong>to change both the boundary and the content-type.</p><p>According to the documentation:</p><pre>fun customMultiPartMixedDataContent(parts: List&lt;PartData&gt;): MultiPartFormDataContent {<br>    val boundary = &quot;WebAppBoundary&quot;<br>    val contentType = ContentType.MultiPart.Mixed.withParameter(&quot;boundary&quot;, boundary)<br>    return MultiPartFormDataContent(parts, boundary, contentType)<br>}</pre><p>With this implementation, the code would look like this:</p><pre>suspend fun uploadScholarshipDocument(uploadUrl: String, file: File){<br><br>val response = client.put(uploadUrl) {<br>    body = customMultiPartMixedDataContent(file = file, parts = formData { <br>        this.appendInput(key = “Input key”, headers = Headers.build {<br>            append(HttpHeaders.ContentDisposition, &quot;filename=${file.name}&quot;)<br>            append(HttpHeaders.ContentLength, file.length())<br>            append(HttpHeaders.ContentType, mimeType)<br>        }, size = file.length(), block = {<br>            buildPacket { writeFully(file.readBytes()) }<br>        })<br>    })<br>} <br>}<br><br>private fun getContentTypeFromFileMimeType(file: File): ContentType {<br>    val extension = file.extension<br><br>    return when (MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: &quot;&quot;) {<br>        &quot;image/jpeg&quot; -&gt; ContentType.Image.JPEG<br>        &quot;image/png&quot; -&gt; ContentType.Image.PNG<br>        &quot;application/pdf&quot; -&gt; ContentType.Application.Pdf<br>        else -&gt; ContentType.Application.OctetStream<br>    }<br>}<br><br>private fun customMultiPartMixedDataContent(file: File, parts: List&lt;PartData&gt;): MultiPartFormDataContent {<br>    return MultiPartFormDataContent(parts = parts, contentType = getContentTypeFromFileMimeType(file))<br>}</pre><p>(I’ve added an util function just to retrieve the ContentType from a MimeType)</p><p>Now the upload works correctly for PDF files. For image files, the upload happens, but the image becomes inaccessible in the S3 bucket, indicating some file corruption during the sending process.</p><h3>How to solve it definitively?</h3><p>Using Retrofit, the solution is quite simple based on this <a href="https://gutier.io/post/android-upload-file-to-aws-s3-bucket-with-retrofit2/">post</a>, we can pass the file as a RequestBody:</p><pre>interface FileApi {<br>    @PUT<br>    suspend fun uploadFile(<br>        @Header(&quot;Content-Type&quot;) contentType: String, @Url uploadUrl: String, @Body file: RequestBody<br>    ): Response&lt;Unit&gt;<br>}<br><br>val requestBody = file.asRequestBody(mimeType.toMediaTypeOrNull())<br>FileApi.uploadFile(mimeType, uploadUrl, requestBody)</pre><p>However, with Ktor, the solution is to send it as <strong>Binary Data</strong>, adding the necessary headers, and passing the <strong>ByteReadChanne</strong>l as the body. The complete function looks like this:</p><pre>suspend fun uploadFile(uploadUrl: String, file: File) {<br>    val client = AppKtorClient.getClient()<br><br>    val extension = file.extension<br>    val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: &quot;&quot;<br><br>    val response = client.put(uploadUrl) {<br>        headers[HttpHeaders.ContentLength] = file.length().toString()<br>        headers[HttpHeaders.ContentType] = mimeType<br>        setBody(file.readChannel())<br>    }<br>}</pre><p>Note: It’s important to define the `Content-Length` header; if not defined, AWS will return a 501 — Not Implemented error.</p><p>With this, our upload is done correctly, and the files (including images) are accessible from the S3 bucket.</p><p>Happy coding, everyone!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9be71b20b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>