Логотип Error Handling

Error Handling

Организация
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.

Add to TypingMind

Обзор

ИздательRevenueCat
Репозиторийplay-billing-skills
Название навыкаerror-handling
Звёзды
58
Форки
0
Файлы в комплекте
Только инструкции
ЛицензияApache-2.0
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — RevenueCat. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Error Handling в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

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
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Error Handling в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Error Handling, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Error Handling не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

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

Часто задаваемые вопросы

Что делает навык ИИ 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.

Зачем использовать Error Handling в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Error Handling — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Error Handling в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Error Handling?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Error Handling?

С любым количеством. В TypingMind вы можете использовать Error Handling с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Error Handling?

Да. Навык опубликован на GitHub по лицензии Apache-2.0. Издатель — RevenueCat. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Release Openclaw Maintainer

openclaw
ОрганизацияПопулярный

Готовьте, публикуйте, восстанавливайте или проверяйте бета-, стабильные и расширенные стабильные релизы OpenClaw, включая утверждённые обратные переносы изменений.

82.2K
391K
Файлы: 11
Открыть
Логотип openclaw

Release Openclaw Plugin Testing

openclaw
ОрганизацияПопулярный

Планируйте и проводите проверку плагинов OpenClaw перед релизом: проверяйте встроенные плагины, артефакты пакетов, команды жизненного цикла, doctor/fix, обратное преобразование конфигурации, запуск gateway, совместимость SDK, Docker E2E,…

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Solid

openclaw
ОрганизацияПопулярный

Write, port, review, or test Solid 2 UI in OpenClaw (Control UI, plugin views, Canvas hosts), including state ownership, Lit interop during the migration, native overlays, testing, performance, and…

82.4K
391.7K
Файлы: 9
Открыть
Логотип openclaw

Auto Qa

openclaw
ОрганизацияПопулярный

Проводите масштабные автономные кампании QA и проверки в реальном времени и под нагрузкой во всех подсистемах OpenClaw, подтверждайте исправления и формируйте отчёт с доказательствами, который можно продолжить.

82.2K
391K
Файлы: 5
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇