Get started
Swift SDK
Fetch data

Errors and retries

Errors and retries

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

Catch an error

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.

Pick the error for the status

StatuskindMeans
400.badRequestThe request is invalid
401.authenticationThe key is unknown, or the token expired or was minted without user_id
402.billingYour agreement does not cover the call
403.forbiddenA scope, a domain or a role is missing
404.notFoundNo such resource for this credential
405.methodNotAllowedNo such method on that path
409.conflictA conflict, such as a lock
409.idempotencyKeyInUseThe first request with this key is still running
409.idempotentAnswerUnavailableThe write was made, but its answer is gone: read the resource, never send the write again
412.preconditionFailedThe resource changed since you read it
413.payloadTooLargeThe body is over the operation's limit
429.rateLimitA limit is spent (wait retryAfter), or a ceiling is full (limitReached)
5xx.serverThe API failed
200.dataA Data API field failed, so the operation did not happen

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

Match an error code

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

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)
  }
}

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:

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

Timeouts and cancellation

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

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.

Watch every answer

onResponse is told of every answer, successes included:

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.

Next steps

Last updated