Get started

Errors and retries

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

Catch an error

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

StatusClassMeans
400BadRequestExceptionThe request is invalid
401AuthenticationExceptionThe key is unknown, or the token expired or was minted without user_id
402BillingExceptionYour agreement does not cover the call
403ForbiddenExceptionA scope, a domain or a role is missing
404NotFoundExceptionNo such resource for this credential
405MethodNotAllowedExceptionThe operation takes another method
409ConflictExceptionA conflict, such as a lock
409IdempotencyKeyInUseExceptionThe first request with this key is still running
409IdempotentAnswerUnavailableExceptionThe write was made, but its answer is gone: read the resource, never send the write again
412PreconditionFailedExceptionThe resource changed since you read it
413PayloadTooLargeExceptionThe body is too large
429RateLimitExceptionA limit is spent, or a ceiling is full
5xxServerExceptionThe API failed
200DataExceptionA 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.

Match an error code

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

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();

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.

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();

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:

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();

Watch every answer

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

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();

Next steps

Last updated