# Errors and retries

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/errors/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Catch the MountayaException ladder the Kotlin client throws, match error codes, tune retries and timeouts, and cancel calls with coroutines.

Every failed call throws a `MountayaException`. The client retries what is worth retrying before it gives up.

## Catch an error

```kotlin
import com.mountaya.client.ApiException
import com.mountaya.client.BillingException
import com.mountaya.client.ConnectionException
import com.mountaya.client.Mountaya

suspend fun showTour(mountaya: Mountaya) {
    try {
        val itinerary = mountaya.studio.itineraries.getItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
        println(itinerary.data.name)
    } catch (failure: BillingException) {
        // 402: your organization's agreement does not cover this call.
        println("Your agreement does not cover this: ${failure.message}")
    } catch (failure: ApiException) {
        println("${failure.status} ${failure.code} ${failure.errors.firstOrNull()?.message} ${failure.requestId}")
    } catch (failure: ConnectionException) {
        println("No answer")
    }
}
```

`ApiException` is a failure the API answered, with its `status`, `code`, `errors` and `requestId`. A timeout or a dropped connection is a `ConnectionException` instead.

## Pick the error for the status

| Status | Class | Means |
| --- | --- | --- |
| `400` | `BadRequestException` | The request is invalid |
| `401` | `AuthenticationException` | The key is unknown, or the token expired or was minted without `user_id` |
| `402` | `BillingException` | Your agreement does not cover the call |
| `403` | `ForbiddenException` | A scope, a domain, or a role is missing |
| `404` | `NotFoundException` | No such resource for this credential |
| `405` | `MethodNotAllowedException` | The operation takes another method |
| `409` | `ConflictException` | A conflict, such as a lock |
| `409` | `IdempotencyKeyInUseException` | The first request with this key is still running |
| `409` | `IdempotentAnswerUnavailableException` | The write was made, but its answer is gone: read the resource |
| `412` | `PreconditionFailedException` | The resource changed since you read it |
| `413` | `PayloadTooLargeException` | The body is too large |
| `429` | `RateLimitException` | A limit is spent, or a ceiling is full (`LIMIT_REACHED`) |
| `5xx` | `ServerException` | The API failed |
| `200` | `DataException` | A Data API field failed, so the operation did not happen |

A `402` is fixed in your agreement or billing settings, not in code. Its message says which.

- The ladder: `MountayaException` (abstract, every error; carries `name`, the contract's name of its class, and `idempotencyKey` where the request carried one) → `ApiException` (open; any status without a class of its own) → `BadRequestException` (400), `AuthenticationException` (401), `BillingException` (402), `ForbiddenException` (403), `NotFoundException` (404), `MethodNotAllowedException` (405), `ConflictException` (409, open) → `IdempotencyKeyInUseException` and `IdempotentAnswerUnavailableException` (both 409), `PreconditionFailedException` (412), `PayloadTooLargeException` (413), `RateLimitException` (429), `ServerException` (5xx), `DataException` (a Data API `200` whose `errors` say the operation did not happen, or one with no `data`).
- Not API errors, extending `MountayaException` directly: `ConnectionException` (no answer: the network, an attempt past its timeout, a stream that stalled, a body that broke off, a success whose body is not JSON), `ConfigurationException` (refused locally before sending), `SelectionException` (a `select` naming a field the schema lacks; `path` says where). `mountaya-admin` adds `WebhookSignatureException`, a `MountayaException` too.
- Kotlin names every class `…Exception` where TypeScript names it `…Error`. The ladder grows with the contract, so a `when` over an error keeps an `else`.
- An `ApiException` carries `status`, `code` (its first entry's), `errors` (each an `ErrorEntry` with `message`, `code` and `path`), `metadata` (a lock's `409` names the member holding it at `metadata.holder`), `requestId`, `rateLimit` and `retryAfter`, a `Duration` from `Retry-After`.
- The message ends on the next step where the status names one: the credential on a `401`, where a `402`'s remedies are taken, the scope on a `403`, a stale tag on a `412`, the wait or the ceiling on a `429`, then the request id.
- The exception that caused one, the exchange's or the decoder's, rides as `cause`, never as the type you catch. A decoder's failure carries no byte of the answer, so no token reaches your logs.
- `isMountayaException(throwable)` and `isApiException(throwable)` classify by `name`, so a crash reporter's filter tells them apart without a `when`; a class of your own implementing `NamedException` with a name of the family is recognised too.
- `IdempotentAnswerUnavailableException.answer` (an `IdempotentAnswer`) carries the first answer's `status`, `location` and `etag`. Read the resource; sending the write under a new key makes it twice.
- A ceiling is a `RateLimitException` with `code == ApiErrorCode.LimitReached`, whose `metadata` names the limit, what it allows and what is held; it names no wait and is never retried.

## Match an error code

Branch on a code by its `ApiErrorCode` constant. `hasCode` asks every entry, not only the first:

```kotlin
import com.mountaya.client.ApiException
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.ApiErrorCode

suspend fun publishTour(mountaya: Mountaya) {
    try {
        mountaya.studio.itineraries.postItineraryPublication("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
    } catch (failure: ApiException) {
        when {
            failure.code == ApiErrorCode.LimitReached -> println("Free a place or change your agreement.")
            failure.hasCode(ApiErrorCode.ValidationFailed) -> failure.errors.forEach { println(it.message) }
            else -> throw failure
        }
    }
}
```

- `ApiErrorCode` (in `com.mountaya.client.generated`) is one vocabulary for the Map Studio, Tile and Data APIs, an open value class whose constants are every code the three declare: `BadRequest`, `ValidationFailed`, `Unauthorized`, `PaymentRequired`, `Forbidden`, `NotFound`, `MethodNotAllowed`, `Conflict`, `IdempotencyKeyInUse`, `IdempotencyAnswerUnavailable`, `PreconditionFailed`, `PayloadTooLarge`, `TooManyRequests`, `LimitReached`, `InternalError`, `NotImplemented`, `BadGateway`, `ServiceUnavailable`, `GatewayTimeout`, `AiProviderNotConfigured`, `RedeliveryInProgress`, `SecretRotationInOverlap`.
- A code a later release sends is kept as sent (`ApiErrorCode("NEW_CODE")`), so a `when` over a code keeps an `else`. Never compare a string you spell.
- The code is reported beside the class and never chooses it: a `402` is always `BillingException`, coded `PAYMENT_REQUIRED`, and a `402` whose second entry is `FORBIDDEN` answers `hasCode(ApiErrorCode.Forbidden)` too.
- An entry about one field names it in `path`: on REST and the Tile API from the root of the request (`["request", "body", "name"]`), on the Data API from the root of the input.
- The vocabulary and the order of a request's checks are on [errors](https://docs.mountaya.com/en/apis/conventions/errors.md).

## Retries

Retries are on by default: two retries with backoff, on `429`, `502`, `503`, `504` and dropped connections. Writes are retried safely, because each one carries an idempotency key.

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.client.RequestOptions
import com.mountaya.client.RetryPolicy
import kotlin.time.Duration.Companion.seconds

suspend fun searchAsYouType(publishableKey: String, query: String) {
    val mountaya = Mountaya(Credential.Publishable(publishableKey), retry = RetryPolicy(maxRetries = 3, waitBudget = 120.seconds))
    // A search box that asks again on every keystroke wants no retry.
    val found = mountaya.studio.itineraries.getItineraries(RequestOptions(retry = RetryPolicy(maxRetries = 0))) { q = query }
    println(found.data.map { it.name })
    mountaya.close()
}
```

- `RetryPolicy(maxRetries = 2, baseDelay = 500.milliseconds, maxDelay = 30.seconds, waitBudget = 60.seconds)` is the default (`RetryPolicy.standard`): two attempts after the first, each wait drawn with full jitter up to a ceiling that doubles from `baseDelay` to `maxDelay`, all waits out of one `waitBudget`. Set it per client (`retry =`) or per call (`RequestOptions(retry = …)`).
- Repeated: a `429` whatever the operation, except a ceiling (`LIMIT_REACHED`), never repeated; a `502`, `503`, `504` or dropped connection only where the operation is idempotent or carries an `Idempotency-Key`, which every write does; and a `409` coded `IDEMPOTENCY_KEY_IN_USE`, asked again at least a second apart while the budget lasts, `maxRetries` not counting those. Never repeated: a `412`, a `409` coded `IDEMPOTENCY_ANSWER_UNAVAILABLE`, and any other `4xx`.
- `Retry-After` (seconds or an HTTP date, a date's wait rounded up to the whole second) replaces the schedule. A wait that does not fit the budget is not taken, and the error arrives with `retryAfter` set.
- A spent daily bound names the seconds to the next UTC day, and a spent monthly allowance the seconds to the next billing period: no budget waits for either, so the error arrives at once. Stop calling that API until `retryAfter` has passed.
- Never wrap a call in a retry loop of your own: the client's retries and yours multiply.

## Timeouts and cancellation

The client's timeout is 30 seconds. A call you no longer want is withdrawn by cancelling its coroutine:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.client.RequestOptions
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.time.Duration.Companion.seconds

suspend fun quickRead(mountaya: Mountaya) {
    // At most 5 seconds for each attempt.
    val itinerary =
        mountaya.studio.itineraries.getItinerary(
            "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
            options = RequestOptions(timeout = 5.seconds),
        )
    // The whole call withdrawn at 10 seconds, retries included.
    val again = withTimeoutOrNull(10.seconds) { mountaya.studio.itineraries.getItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21") }
    println("${itinerary.data.name} ${again?.status}")
}
```

- An attempt is allowed the longer of the client's `timeout` (30 seconds by default) and the operation's budget plus 5 seconds: 35 seconds for REST and Data API operations, 60 seconds for an import and its preview (`postItineraryImport`, `postItineraryPreview`, which state 55). An event stream states no budget and takes the client's. A call's own `RequestOptions(timeout = …)` stands over both. The budget runs from the attempt's start to the last byte of its answer, the wait for a first session token included, and does not bound the retry sequence. An attempt that runs out is a `ConnectionException`, repeated as one where the call is safe to repeat. The timeout also bounds a wait for the first session token.
- A call is withdrawn by cancelling its coroutine: a `Job`'s `cancel()`, the end of its scope (`viewModelScope`, a composable's `LaunchedEffect`), or `withTimeout`. A coroutine cancelled before the call starts sends nothing; a cancellation during a request or a wait settles it at once. The call throws its `CancellationException` as it is, never an error of the ladder, and it is never repeated.
- Always rethrow `CancellationException` in a `catch (e: Exception)`, or catch the ladder's classes alone, so structured concurrency still works.
- A stream or a walk ends the same way when the coroutine collecting it is cancelled.
- Every wait runs on the caller's coroutine time, so a test under `runTest` spends none once it passes `StandardTestDispatcher(testScheduler)` as `dispatcher` (see [testing](https://docs.mountaya.com/en/sdks/kotlin/testing.md#time)).

## Watch every answer

`onResponse` hears every answer, successes included:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya

fun watchedClient(publishableKey: String): Mountaya =
    Mountaya(
        Credential.Publishable(publishableKey),
        onResponse = { report ->
            val minute = report.rateLimit?.policies?.firstOrNull { it.name == "minute" }
            if (minute?.remaining == 0L) println("${report.operationId} (${report.status}, ${report.requestId}) spent the minute")
        },
    )
```

Quote the `requestId` to support: it is the id the API recorded the request under.

- The hook is told, for every attempt an answer came back to, a `ResponseReport`: `operationId`, `surface`, `status`, `attempt`, `isReplayed` (answered from an `Idempotency-Key`), `requestId` and `rateLimit`, a `RateLimitState` whose `policies` each carry `name`, `quota`, `window`, `remaining` and `reset`, read from the `RateLimit-Policy` and `RateLimit` fields the Data API and the Tile API send.
- Policy names: `minute`, and `month` for the monthly allowance unless an agreement leaves it unlimited; `address`, `member`, `studio-embedded` and `share` for the other bounds. See [rate limits](https://docs.mountaya.com/en/apis/conventions/rate-limits.md).
- The hook does not suspend, and nothing it does, an exception it throws included, changes what a call answers. The client delays no request on the state.
- To watch traffic by address rather than by operation, wrap the `HttpExchange` (see [testing](https://docs.mountaya.com/en/sdks/kotlin/testing.md#fetch)). An `ExchangeRequest` prints its method and address, never the credential's headers.

## Next steps

- [Pagination and safe writes](https://docs.mountaya.com/en/sdks/kotlin/pagination.md): Whole listings, idempotency keys, `ifMatch`.
- [Troubleshooting](https://docs.mountaya.com/en/sdks/kotlin/troubleshooting.md): The errors developers hit first.
