Get started
Kotlin SDK
Fetch data

Errors and retries

Errors and retries

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

Catch an error

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

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
412PreconditionFailedExceptionThe resource changed since you read it
413PayloadTooLargeExceptionThe body is too large
429RateLimitExceptionA limit is spent, or a ceiling is full (LIMIT_REACHED)
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

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

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

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

Timeouts and cancellation

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

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

Watch every answer

onResponse hears every answer, successes included:

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.

Next steps

Last updated