Logo Error Handling

Error Handling

Tổ chức
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

Tổng quan

Nhà phát hànhRevenueCat
Kho mãplay-billing-skills
Tên kỹ năngerror-handling
Sao
58
Bản fork
0
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépApache-2.0
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được RevenueCat công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Error Handling trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

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
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Error Handling trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Error Handling ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Error Handling với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

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

Câu hỏi thường gặp

Kỹ năng AI Error Handling làm được gì?

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.

Vì sao nên dùng Error Handling trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Error Handling là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Error Handling trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/RevenueCat/play-billing-skills/tree/main/google-play/error-handling. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Error Handling?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Error Handling với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Error Handling với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Error Handling có miễn phí không?

Có. Kỹ năng này được RevenueCat phát hành trên GitHub theo giấy phép Apache-2.0. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇