# Errors and retries

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

Catch the one MountayaError the Swift client throws, branch on its kind and code, and tune retries, timeouts and cancellation.

Every failure the SDK throws is a `MountayaError`. The client retries what is worth retrying before it gives up.

## Catch an error

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? ""))

do {
  _ = try await mountaya.studio.itineraries.getItinerary(
    itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
} catch let error as MountayaError {
  switch error {
  case .api(let failure) where failure.kind == .billing:
    // 402: your organization's agreement does not cover this call.
    print("This call is not part of your agreement.")
  case .api(let failure):
    print(
      failure.status, failure.code?.rawValue ?? "", failure.errors.first?.message ?? "",
      failure.requestId ?? "")
  case .connection:
    print("No answer")
  default:
    throw error
  }
}
```

`.api` is an answer the API sent, with its `status`, `code`, `errors` and `requestId`. `.connection` is a call that got no answer.

- `MountayaError` is a non-frozen enum: `.api(APIError)`, `.connection(ConnectionError)`, `.configuration(ConfigurationError)` (refused locally before sending), `.selection(SelectionError)` (a `select` naming a field the schema lacks), `.webhookSignature(WebhookSignatureError)` (a refused webhook delivery). The ladder grows with the contract, so an exhaustive `switch` ends in `@unknown default`.
- Swift names the cases of one enum where the TypeScript SDK has a class per status: the status's row is `APIError.kind`, and `kind.name` is the contract's class name (`NotFoundError`).
- A cancelled task throws `CancellationError` as it is, never wrapped and never retried.
- `message` (which `description` prints) is written for a log line and ends on what to do where the status names a step: the credential on a `401`, where a `402`'s remedies are taken, the scope on a `403`, a stale tag on a `412`, and on a `429` the wait, a ceiling's remedies, or the instant a spent monthly allowance renews. The error that caused one (a `URLError`, a `DecodingError`) rides as `cause`, never as the type you catch.
- `APIError` carries `status`, `kind`, `code` (the first entry's), `errors` (`[ErrorEntry]`, each `message`, `code`, `path`), `metadata` (a `JSONValue?`: a lock's holder on a `409`, a ceiling's `{ limit, allowed, used }` on a `429`), `retryAfter` (`Duration?`), `requestId`, `rateLimit`, `etag` (the resource's current tag on a `412`), `idempotencyKey` and `unavailableAnswer`.
- `isMountayaError(_:)` and `isAPIError(_:)` answer for any `Error` by the contract's name (`NamedError.name`), for code that holds `any Error`, a logger or a crash reporter.
- `MountayaError.idempotencyKey` is the key a failed write was sent with, on every case that carries one.

## Pick the error for the status

| Status | `kind` | Means |
| --- | --- | --- |
| `400` | `.badRequest` | The request is invalid |
| `401` | `.authentication` | The key is unknown, or the token expired or was minted without `user_id` |
| `402` | `.billing` | Your agreement does not cover the call |
| `403` | `.forbidden` | A scope, a domain or a role is missing |
| `404` | `.notFound` | No such resource for this credential |
| `405` | `.methodNotAllowed` | No such method on that path |
| `409` | `.conflict` | A conflict, such as a lock |
| `409` | `.idempotencyKeyInUse` | The first request with this key is still running |
| `409` | `.idempotentAnswerUnavailable` | The write was made, but its answer is gone: read the resource, never send the write again |
| `412` | `.preconditionFailed` | The resource changed since you read it |
| `413` | `.payloadTooLarge` | The body is over the operation's limit |
| `429` | `.rateLimit` | A limit is spent (wait `retryAfter`), or a ceiling is full (`limitReached`) |
| `5xx` | `.server` | The API failed |
| `200` | `.data` | A Data API field failed, so the operation did not happen |

A `402` is fixed in your agreement or billing settings, not in code.

- Every `APIError.Kind`: `.badRequest` (400), `.authentication` (401), `.billing` (402), `.forbidden` (403), `.notFound` (404), `.methodNotAllowed` (405), `.conflict` (409), `.idempotencyKeyInUse` (409 coded `IDEMPOTENCY_KEY_IN_USE`), `.idempotentAnswerUnavailable` (409 coded `IDEMPOTENCY_ANSWER_UNAVAILABLE`), `.preconditionFailed` (412), `.payloadTooLarge` (413), `.rateLimit` (429), `.server` (any 5xx), `.data` (a Data API answer carrying errors under a success status), `.other` (any other status). `kind.isConflict` is true for all three 409 kinds.
- `.idempotentAnswerUnavailable`: a repeat of an `Idempotency-Key` whose first request made its write and whose answer cannot be given again. `unavailableAnswer` (`APIError.IdempotentAnswer`) carries the first answer's `status`, `location` and `etag` where it had them. Read the resource; never send the write again under a new key.
- A `402` is always `.billing`, whatever its entry says (`PAYMENT_REQUIRED`). The API checks the product before the key's scopes, so a key with a scope whose product the organization lacks gets `402`, not `403`.
- A `403` is a scope the key lacks, a resource outside the key's organization, an app or page the organization does not allow, or a member without the role.
- `ConnectionError` is a failure with no answer: the network, an attempt past its timeout, a stream that went silent, a body that broke off, or a success whose body is not JSON.
- The code vocabulary and the order of a request's checks are on [errors](https://docs.mountaya.com/en/apis/conventions/errors.md).

## Match an error code

`code` is an `APIErrorCode`, so you branch on a member instead of a string. `hasCode(_:)` looks at every entry:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")))

do {
  _ = try await mountaya.studio.itineraries.postItineraryPublication(
    itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
} catch MountayaError.api(let failure) where failure.code == .limitReached {
  print("Free a place or change your agreement.")
} catch MountayaError.api(let failure) where failure.hasCode(.validationFailed) {
  for entry in failure.errors {
    print(entry.message)
  }
}
```

- `APIErrorCode` is the one vocabulary of every API's codes: `.badRequest`, `.unauthorized`, `.paymentRequired`, `.forbidden`, `.notFound`, `.methodNotAllowed`, `.conflict`, `.preconditionFailed`, `.payloadTooLarge`, `.validationFailed`, `.tooManyRequests`, `.limitReached`, `.idempotencyKeyInUse`, `.idempotencyAnswerUnavailable`, `.internalError`, `.notImplemented`, `.badGateway`, `.serviceUnavailable`, `.gatewayTimeout`, `.aiProviderNotConfigured`, `.redeliveryInProgress`, `.secretRotationInOverlap`.
- It is open: a code a later API release sends is kept as sent, `APIErrorCode(rawValue:)`, and never refused. `rawValue` is the wire's text (`LIMIT_REACHED`).
- `code` is the first entry's, the one the ladder classifies by. One refusal may name several codes, so `hasCode(_:)` asks every entry.
- A ceiling is a `.rateLimit` coded `.limitReached`: the seats, the published itineraries or zones, the webhook endpoints, the invitations waiting at once, or a personal space's itineraries. Its `metadata` names the ceiling with what it allows and what is held, its `retryAfter` is nil, and the client never repeats it.
- An entry about one field says which in `path`: from the root of the request on REST and the Tile API (`["request", "body", "name"]`), from the root of the input on the Data API.

## Retries

Retries are on: two retries with backoff, on `429`, `502`, `503`, `504` and dropped connections. Change the policy for a client, or for one call:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(
    key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "",
    sessionToken: .value(environment["MOUNTAYA_SESSION_TOKEN"] ?? "")),
  retry: try RetryPolicy(maxRetries: 3, waitBudget: .seconds(120)))

// A search box that asks on every keystroke wants no retries.
let typed = "Mont-Blanc"
let matches = try await mountaya.studio.itineraries.getItineraries(
  query: .init { $0.q = typed },
  options: RequestOptions(retry: try RetryPolicy(maxRetries: 0)))
print(matches.data.map(\.name))
```

- `RetryPolicy(maxRetries:baseDelay:maxDelay:waitBudget:)`, defaults `2`, `.milliseconds(500)`, `.seconds(30)`, `.seconds(60)` (`RetryPolicy.standard`). Waits are drawn up to a ceiling that doubles from `baseDelay` to `maxDelay`, all out of the one `waitBudget`. A policy that cannot work throws `MountayaError.configuration` where it is built.
- Repeated: a `429` whatever the operation, except a ceiling (`LIMIT_REACHED`); a `502`, `503`, `504` or a dropped connection where the operation is idempotent or carries an `Idempotency-Key`, which every write does. A `4xx` about your request is never repeated, a `412` least of all.
- `Retry-After`, in seconds or as an HTTP date, replaces the schedule; a date is waited out to the whole second after it. A wait that does not fit the budget is not taken and the error reaches you with `retryAfter` set.
- A `409` coded `IDEMPOTENCY_KEY_IN_USE` is asked again for as long as `waitBudget` lasts, apart from `maxRetries`; then `.idempotencyKeyInUse` is thrown.
- A spent daily or monthly allowance names a wait no budget covers: the error arrives at once. Stop calling until `retryAfter` has passed.

## Timeouts and cancellation

The client's timeout is 30 seconds. Give one call 5 seconds, and withdraw the whole call by cancelling its task:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? ""))

let call = Task {
  try await mountaya.studio.itineraries.getItinerary(
    itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
    options: RequestOptions(timeout: .seconds(5)))
}
// Withdraw the call, retries included, if it has not answered after 10 seconds.
Task {
  try? await Task.sleep(for: .seconds(10))
  call.cancel()
}
do {
  print(try await call.value.data.name)
} catch is CancellationError {
  print("withdrawn")
}
```

A cancelled call throws `CancellationError`, never a `MountayaError`. SwiftUI's `.task` cancels for you when its view goes away.

- `timeout` bounds each attempt, not the retry sequence: from the attempt's start to the last byte of its answer, the wait for a first session token included. An attempt is allowed the longer of the client's timeout (30 seconds unless `Mountaya(timeout:)` names another) and the operation's own budget plus 5 seconds: 35 seconds for REST and Data API operations, 60 seconds for `postItineraryImport` and `postItineraryPreview`. An event stream states no budget and takes the client's. A call's `RequestOptions(timeout:)` stands over both, shorter or longer.
- An attempt past its timeout fails as `.connection` and is retried where the call is safe to repeat. The timeout also bounds a wait for the first session token.
- A task cancelled before the call starts sends nothing. A cancellation during a request or a wait between two attempts settles the call at once. A stream or a walk ends the same way when the task reading it is cancelled.

## Watch every answer

`onResponse` is told of every answer, successes included:

```swift
import Foundation
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let mountaya = try Mountaya(
  credential: .publishable(key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? ""),
  onResponse: { report in
    let minute = report.rateLimit?.policies.first { $0.name == "minute" }
    if minute?.remaining == 0 {
      print("\(report.operationId) spent the minute, request \(report.requestId ?? "")")
    }
  })
```

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

- `ResponseReport` carries `operationId`, `surface`, `status`, `attempt`, `isReplayed` (answered from an `Idempotency-Key`), `requestId` and `rateLimit`: a `RateLimitState` of `policies`, each with `name`, `quota`, `window`, `remaining` and `reset`, read from the `RateLimit-Policy` and `RateLimit` fields the Data API and the Tile API send. The Map Studio API sends neither.
- Policy names: `minute`, and `month` 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 is a function that throws nothing, so nothing it does changes what a call answers. The client records nothing of its own.

## Next steps

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