# Errors and retries

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

Catch the MountayaException ladder with on clauses, match ApiErrorCode, and tune retries, timeouts and cancellation.

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

## Catch an error

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
try {
  await mountaya.studio.itineraries.getItinerary(
    itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
  );
} on BillingException {
  // 402: your organization's agreement does not cover this call.
  print('This needs a change to your Mountaya agreement.');
} on ApiException catch (failure) {
  print(
    '${failure.status} ${failure.code} '
    '${failure.errors.firstOrNull?.message} ${failure.requestId}',
  );
} on ConnectionException {
  print('No answer.');
}
await mountaya.close();
```

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

## 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, never send the write again |
| `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 |
| `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.

- Every class ends in `Exception` where the contract's ends in `Error`, and extends `MountayaException`, an `Exception` a caller handles. API failures extend `ApiException`. Full ladder: `ApiException` (any other status, and the base of the others), `BadRequestException` (400), `AuthenticationException` (401), `BillingException` (402), `ForbiddenException` (403), `NotFoundException` (404), `MethodNotAllowedException` (405), `ConflictException` (409), `IdempotencyKeyInUseException` and `IdempotentAnswerUnavailableException` (both 409, both `ConflictException`), `PreconditionFailedException` (412), `PayloadTooLargeException` (413), `RateLimitException` (429), `ServerException` (5xx), `DataException` (a Data API `200` whose `errors` say the operation did not happen). Not API errors, extending `MountayaException` directly: `ConnectionException` (no answer: network, timeout, a broken body, a success that is not JSON), `ConfigurationException` (refused before sending, with a `message`), `SelectionException` (a `select:` naming a field the tree lacks, with its `path`). `WebhookSignatureException` is a `MountayaException` the admin unit publishes.
- `AbortedException` is not a `MountayaException`: it is the reason an `AbortSignal` aborted with none, and a withdrawn call throws its signal's reason.
- `on` tells the classes apart, most specific first. None is `sealed`: the ladder grows with the contract, so a `switch` over them keeps a default.
- Each class declares the contract's name as `name`. `isMountayaException(value)` and `isApiException(value)` read it, so they hold in a build made with `--obfuscate`, and recognise a failure of your own type that implements `NamedException`.
- An `ApiException` carries `status`, `code` (the first entry's `ApiErrorCode`), `errors` (each an `ErrorEntry` with `message`, `code`, `path`), `metadata`, `requestId`, `retryAfter` (a `Duration`), `rateLimit`, `etag`, `idempotencyKey`, and `cause`, the exception that caused it (a `SocketException`, a `FormatException`), never the type you catch.
- The message ends on what to do: the credential to check 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.
- `IdempotentAnswerUnavailableException` (`409`, `IDEMPOTENCY_ANSWER_UNAVAILABLE`): the write was made, and its answer is gone. Its `answer` (`IdempotentAnswer`) carries `status`, `location` and `etag` where the first answer had them. Read the resource; never send the write again under a new key.
- A test builds the failure it handles through its public constructor: `NotFoundException()`, `RateLimitException(retryAfter: Duration(seconds: 30))`, `ApiException.of(status)` for the class a status maps to.
- The code vocabulary and the order in which a request's checks run are on [errors](https://docs.mountaya.com/en/apis/conventions/errors.md).

## Match an error code

`code` is an `ApiErrorCode`, the same type for every API. `hasCode` asks whether any entry carries a code:

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionToken = String.fromEnvironment('MOUNTAYA_SESSION_TOKEN');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: const .value(sessionToken)),
);
try {
  await mountaya.studio.itineraries.postItineraryPublication(
    itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
  );
} on ApiException catch (failure) {
  if (failure.hasCode(ApiErrorCode.limitReached)) {
    print('Free a place or change your agreement.');
  } else if (failure.hasCode(ApiErrorCode.validationFailed)) {
    for (final entry in failure.errors) {
      print(entry.message);
    }
  }
}
await mountaya.close();
```

- `ApiErrorCode` holds every code the Map Studio API, the Tile API and the Data API declare, as constants: `aiProviderNotConfigured`, `badGateway`, `badRequest`, `conflict`, `forbidden`, `gatewayTimeout`, `idempotencyAnswerUnavailable`, `idempotencyKeyInUse`, `internalError`, `limitReached`, `methodNotAllowed`, `notFound`, `notImplemented`, `payloadTooLarge`, `paymentRequired`, `preconditionFailed`, `redeliveryInProgress`, `secretRotationInOverlap`, `serviceUnavailable`, `tooManyRequests`, `unauthorized`, `validationFailed`.
- It is an open extension type over the code's text: a code a later API release sends is kept as sent, so a `switch` keeps a default.
- `hasCode(code)` asks every entry, the first or another, since one refusal may carry several codes.
- A ceiling is a `RateLimitException` coded `limitReached` (`LIMIT_REACHED`): seats, published itineraries or zones, webhook endpoints, invitations waiting, a personal space's itineraries. Its `metadata` names the ceiling (`limit`, `allowed`, `used`), its `retryAfter` is `null`, and it is never repeated.
- An entry about one field says which in `path`: from the request's root on REST and the Tile API, from the input's root on the Data API.

## 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.

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

// A longer budget of waits for this client.
final mountaya = Mountaya(
  credential: .publishable(key: publishableKey),
  retry: const RetryPolicy(maxRetries: 3, waitBudget: Duration(seconds: 120)),
);

// A search box that asks on every keystroke wants no retries.
const typed = 'mont';
await mountaya.studio.itineraries.getItineraries(
  query: rest_schema.GetItinerariesQuery(q: typed),
  options: const RequestOptions(retry: RetryPolicy(maxRetries: 0)),
);
await mountaya.close();
```

- `RetryPolicy.standard`: `maxRetries` 2, `baseDelay` 500 ms, `maxDelay` 30 s, `waitBudget` 60 s. Waits are drawn up to a ceiling that doubles from 500 ms to 30 s, or what a `Retry-After` names (whole seconds or an HTTP date, rounded up), all out of the one budget: a wait that does not fit is not taken, and the error reaches your code.
- Repeated: a `429` whatever the operation (but a ceiling, `LIMIT_REACHED`), and a `502`, `503`, `504` or dropped connection where the operation is idempotent or carries an `Idempotency-Key`. A `4xx` that is a statement about your request is never repeated, a `412` least of all.
- A `409` coded `IDEMPOTENCY_KEY_IN_USE` is asked again while the budget lasts, then raised as `IdempotencyKeyInUseException`.
- A spent daily or monthly allowance names a `Retry-After` past the budget: the error arrives at once. Read `failure.retryAfter` and stop calling that API until it has passed.
- Every jitter and every key the client draws comes from the `RandomSource` you hand it as `random:`.

## Timeouts and cancellation

The client's timeout is 30 seconds. Give one call a shorter one, and withdraw the whole call, retries included, with an `AbortSignal`:

```dart
import 'dart:async';

import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
try {
  await mountaya.studio.activities.getActivities(
    options: RequestOptions(
      // Each attempt waits 5 seconds for an answer.
      timeout: const Duration(seconds: 5),
      // The whole call, its retries included, is withdrawn at 10 seconds.
      signal: AbortSignal.timeout(const Duration(seconds: 10)),
    ),
  );
} on TimeoutException {
  print('Withdrawn after ten seconds.');
} on ConnectionException {
  print('No answer within five seconds, after every retry.');
}
await mountaya.close();
```

- `timeout` (the client's, 30 s unless you name one, or a call's `RequestOptions.timeout`) bounds each attempt's wait for an answer, not the retry sequence. An attempt is allowed the longer of the client's timeout and the operation's own budget plus 5 seconds: 35 seconds for a REST or Data API operation (budget 30 s), 60 seconds for `postItineraryImport` and `postItineraryPreview` (budget 55 s). Event streams state no budget. A call's own `RequestOptions.timeout` stands over both.
- An attempt that reaches its timeout fails as a `ConnectionException`, and is retried where the call is safe to repeat.
- `AbortSignal()` with `abort([reason])`, `AbortSignal.timeout(duration)` (its reason a `TimeoutException`), `AbortSignal.any(signals)` and `AbortSignal.fromFuture(future)`. A call aborted before it starts sends nothing; an abort during a request or a wait settles it at once. It throws the signal's own reason, an `AbortedException` where `abort()` names none, and is never repeated: your cancellation is no failure of the API.
- A `Stream` the client returns (a walk, an event stream) is withdrawn by the signal of its `options:` too, or by cancelling its subscription. However it ends, it lets your signal go.

## Watch every answer

`onResponse` hears every attempt an answer came back to, successes included:

```dart
import 'package:mountaya_client/mountaya_client.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(
  credential: .publishable(key: publishableKey),
  onResponse: (report) {
    final policies = report.rateLimit?.policies ?? const [];
    for (final minute in policies.where((policy) => policy.name == 'minute')) {
      if (minute.remaining == 0) {
        print('${report.operationId} (${report.status}) spent the minute');
      }
    }
  },
);
await mountaya.close();
```

- A `ResponseReport` carries `operationId`, `surface` (`Surface.rest`, `tiles` or `data`), `status`, `attempt`, `isReplayed` (an answer replayed for an `Idempotency-Key`), `requestId` and `rateLimit`, a `RateLimitState` whose `policies` each have `name`, `quota`, `window`, `remaining` and `reset`.
- 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 runs where what it throws is dropped, so nothing it does changes what a call answers. The state is for watching, never for steering: the client delays no request on it.
- The client records nothing itself: no logging, no telemetry. `onResponse` is how an app watches its traffic.

## Next steps

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