Logo di Error Handling

Error Handling

Organizzazione
RevenueCat
error-handling

Use this skill when designing error handling and retry strategy for the Play Billing Library. Classifies every BillingResponseCode into recoverable, non recoverable, and user driven categories and builds a retry plan with exponential backoff and circuit breaker patterns.

Panoramica

Pubblicato daRevenueCat
Repositoryplay-billing-skills
Nome della skillerror-handling
Stelle
58
Fork
0
File inclusi
Solo istruzioni
LicenzaApache-2.0
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • Tutto nelle istruzioni

    Tutto ciò che serve al modello è nelle istruzioni: nessun file aggiuntivo da sincronizzare.

  • Open source

    Pubblicata da RevenueCat su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Error Handling in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Aggiungi skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.
2

Installa in un altro agente

Qualsiasi agente che legge il formato Agent Skills può usare questa skill: copia la cartella della skill nella directory delle skill di quell'agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/RevenueCat/play-billing-skills.git /tmp/play-billing-skills
mkdir -p .claude/skills
cp -r /tmp/play-billing-skills/google-play/error-handling .claude/skills/error-handling
Dopo la copia, riavvia Claude Code per caricare la nuova skill.

Usala in TypingMind

Attiva Error Handling in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Error Handling non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Error Handling non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

Error Handling and Retry Strategies

Every Play Billing Library call can fail. Network connections drop, the Play Store app updates or restarts, users cancel purchases, and payment methods get declined. This skill gives you a phased path from reading a BillingResult to shipping a retry layer that recovers gracefully without hammering Google's servers.

Phase 1: Read BillingResult correctly

Every PBL operation returns a BillingResult with two fields. Treat them asymmetrically.

  • responseCode is the integer constant you branch on. Always use the constants from BillingClient.BillingResponseCode, never the raw integer.
  • debugMessage is a log only string. Google can change the text at any time, so never parse it and never show it to users.
kotlin
// PBL 9.x
val billingResult = billingClient.acknowledgePurchase(params)
when (billingResult.responseCode) {
    BillingClient.BillingResponseCode.OK -> { /* proceed */ }
    BillingClient.BillingResponseCode.NETWORK_ERROR -> { /* retry */ }
    else -> Log.e("Billing", billingResult.debugMessage)
}

PBL 8.0 added sub response codes, read in PurchasesUpdatedListener with BillingResult.getOnPurchasesUpdatedSubResponseCode() (Kotlin: billingResult.onPurchasesUpdatedSubResponseCode). Two are worth branching on:

  • PAYMENT_DECLINED_DUE_TO_INSUFFICIENT_FUNDS arrives under a top level ERROR and lets you suggest a different payment method instead of a generic failure screen.
  • USER_INELIGIBLE tells you the user does not qualify for the offer, so you can show alternatives they do qualify for.

Not every failure carries a sub response code. Check presence before acting.

Phase 2: Classify every response code

Before you write retry code, place every code in one of four buckets. Retriable codes drive loops. User driven codes drive UI prompts. Cache sync codes drive a refresh then replay. Terminal codes surface an error message and stop.

Response CodeValueCategoryAction
OK0SuccessProceed
USER_CANCELED1IgnoreReturn silently to previous screen
SERVICE_UNAVAILABLE2RetriableExponential backoff
BILLING_UNAVAILABLE3User drivenShow a generic unavailable message with a Try again button; never auto retry
ITEM_UNAVAILABLE4Cache syncRefresh product details
DEVELOPER_ERROR5TerminalFix code, log debugMessage
ERROR6RetriableExponential backoff
ITEM_ALREADY_OWNED7Cache syncRefresh purchases, grant access
ITEM_NOT_OWNED8Cache syncRefresh purchases
NETWORK_ERROR12RetriableSimple retry with short delay
SERVICE_DISCONNECTED-1ReconnectWith enableAutoServiceReconnection(): retry the call (simple in session, backoff in background). Without it: call startConnection, then retry
SERVICE_TIMEOUT-3Retriable (deprecated, not returned since PBL 6)Treat as SERVICE_UNAVAILABLE
FEATURE_NOT_SUPPORTED-2TerminalHide feature in UI

A few classification notes:

  • BILLING_UNAVAILABLE means billing is unavailable for this user or device (outdated Play Store, unsupported country, purchases disabled by an admin, payment method cannot be charged). Never auto retry; offer a "try again" button. As of PBL 9 (with androidx.core 1.9+), a Play Store blocked by the system (for example an OEM customized kids mode) reports BILLING_UNAVAILABLE instead of ERROR, with a "Play Store is blocked" debugMessage. Handle it like any other BILLING_UNAVAILABLE; log the debug message but do not branch on its text.
  • ITEM_ALREADY_OWNED often means a purchase succeeded but your app crashed before processing it. Refresh purchases and grant access instead of showing an error.
  • DEVELOPER_ERROR should never reach production. If you see it in logs, fix the call site (invalid product ID, wrong product type, calling before connection is ready).
  • FEATURE_NOT_SUPPORTED is answered at startup by calling isFeatureSupported once and hiding unsupported features.
  • SERVICE_DISCONNECTED (BillingAction.Reconnect): enable enableAutoServiceReconnection() (PBL 8+) when building the client; with it, Reconnect means retry the call, not call startConnection() yourself.

Model the classification as a sealed action type so decisions are unit testable without a BillingClient:

kotlin
// PBL 9.x
sealed class BillingAction {
    data object Success : BillingAction()
    data object RetrySimple : BillingAction()
    data object RetryBackoff : BillingAction()
    data object Reconnect : BillingAction()
    data object RefreshPurchases : BillingAction()
    data object RefreshProducts : BillingAction()
    data object UserRetry : BillingAction()
    data object Ignore : BillingAction()
    data class Fail(val msg: String) : BillingAction()
}
kotlin
// PBL 9.x
fun decideBillingAction(code: Int) = when (code) {
    BillingResponseCode.OK -> BillingAction.Success
    BillingResponseCode.NETWORK_ERROR -> BillingAction.RetrySimple
    BillingResponseCode.SERVICE_UNAVAILABLE,
    BillingResponseCode.ERROR,
    BillingResponseCode.SERVICE_TIMEOUT -> BillingAction.RetryBackoff
    BillingResponseCode.SERVICE_DISCONNECTED -> BillingAction.Reconnect
    BillingResponseCode.ITEM_ALREADY_OWNED,
    BillingResponseCode.ITEM_NOT_OWNED -> BillingAction.RefreshPurchases
    BillingResponseCode.ITEM_UNAVAILABLE -> BillingAction.RefreshProducts
    BillingResponseCode.BILLING_UNAVAILABLE -> BillingAction.UserRetry
    BillingResponseCode.USER_CANCELED -> BillingAction.Ignore
    else -> BillingAction.Fail("Non retriable: $code")
}

Phase 3: Build the retry layer

Retriable codes split into two policies. Network level noise uses a short fixed delay. Server side overload uses exponential backoff with jitter. Add a circuit breaker on top so a failing downstream stops burning user battery and retry budget.

Simple retry for NETWORK_ERROR

Start at one to two seconds, cap at three attempts, and always check the response code instead of catching exceptions (PBL returns results, it does not throw).

kotlin
// PBL 9.x
suspend fun retryOnBillingError(
    maxAttempts: Int = 3,
    delayMs: Long = 1_000L,
    retriable: Set<Int>,
    block: suspend () -> BillingResult
): BillingResult {
    var last: BillingResult? = null
    repeat(maxAttempts) { attempt ->
        val r = block()
        if (r.responseCode !in retriable) return r
        last = r
        if (attempt < maxAttempts - 1) delay(delayMs)
    }
    return last!!
}

Exponential backoff with jitter for SERVICE_UNAVAILABLE, ERROR, and SERVICE_TIMEOUT

Double the delay each attempt so overloaded services can recover. Add random jitter so thousands of devices do not retry in lockstep after a regional outage.

kotlin
// PBL 9.x
suspend fun retryWithBackoff(
    maxAttempts: Int = 3,
    baseDelayMs: Long = 2_000L,
    factor: Double = 2.0,
    block: suspend () -> BillingResult
): BillingResult {
    var last: BillingResult? = null
    repeat(maxAttempts) { attempt ->
        val r = block()
        if (r.responseCode !in RETRIABLE_BACKOFF) return r
        last = r
        if (attempt < maxAttempts - 1) {
            val base = baseDelayMs * factor.pow(attempt.toDouble())
            val jitter = Random.nextLong(0, baseDelayMs / 2)
            delay(base.toLong() + jitter)
        }
    }
    return last!!
}

With base two seconds and factor two, the waits are 2s then 4s (plus up to 1s jitter each). Three attempts finish inside roughly six seconds of waiting, which is acceptable for an in flight purchase and gives Google room to breathe.

Circuit breaker to stop cascading failures

When a downstream keeps failing, the breaker opens and short circuits further calls for a cooldown window. This protects battery, prevents retry storms, and surfaces a user actionable error quickly.

kotlin
// PBL 9.x
class BillingCircuitBreaker(
    private val threshold: Int = 5,
    private val cooldownMs: Long = 30_000L
) {
    private var failures = 0
    private var openedAt = 0L
    fun isOpen(): Boolean =
        failures >= threshold &&
            System.currentTimeMillis() - openedAt < cooldownMs
    fun recordSuccess() { failures = 0 }
    fun recordFailure() {
        failures++
        if (failures >= threshold) openedAt = System.currentTimeMillis()
    }
}

Wire the breaker around the retry policies so an open circuit skips the call entirely:

kotlin
// PBL 9.x
suspend fun guarded(
    breaker: BillingCircuitBreaker,
    block: suspend () -> BillingResult
): BillingResult {
    if (breaker.isOpen()) return BillingResult.newBuilder()
        .setResponseCode(BillingResponseCode.SERVICE_UNAVAILABLE)
        .setDebugMessage("circuit open").build()
    val r = block()
    if (r.responseCode == BillingResponseCode.OK) breaker.recordSuccess()
    else breaker.recordFailure()
    return r
}

Phase 4: Handle onPurchasesUpdated and user messaging

onPurchasesUpdated is the one callback where wrong error handling directly costs users the content they paid for. Three rules:

  1. Null check purchases even when responseCode is OK.
  2. USER_CANCELED emits zero UI, zero analytics failures, zero prompts. Return to the previous screen.
  3. ITEM_ALREADY_OWNED triggers a purchase refresh and grants access silently. The user already paid.

User messaging maps directly to categories:

  • Retriable in progress: show a subtle loading indicator, never flash errors between attempts.
  • Retries exhausted: "Something went wrong. Please try again." with a retry button.
  • BILLING_UNAVAILABLE: "Purchases aren't available on this device or account right now. Please try again later."
  • Payment declined sub code: "Your payment method was declined. Please update your payment method in Google Play and try again."
  • Never show raw response codes or debugMessage text to users.

Remember to acknowledge successful purchases within three days or Google refunds them automatically.

References

Domande frequenti

Cosa fa la skill IA Error Handling?

Use this skill when designing error handling and retry strategy for the Play Billing Library. Classifies every BillingResponseCode into recoverable, non recoverable, and user driven categories and builds a retry plan with exponential backoff and circuit breaker patterns.

Perché usare Error Handling su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Error Handling è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che la skill smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Error Handling in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling. TypingMind legge il file SKILL.md e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Error Handling?

Qualsiasi modello che colleghi a TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Error Handling?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Error Handling: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Error Handling è gratuita?

Sì. È pubblicata su GitHub da RevenueCat con licenza Apache-2.0. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, template o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Elenco completo

Crea subito il tuo spazio di lavoro AI

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇