Exchange Rate API Error Handling: What Each Error Code Means and What to Do

6 min read

Exchange Rate API Error Handling: What Each Error Code Means and What to Do

Good exchange rate API error handling comes down to one idea: every error belongs to one of three groups. Some you retry, some you fix in your code or configuration, and some you explain to the user. If you treat them all the same, you either hammer the API with doomed retries or show a generic "something went wrong" on a checkout page.

This article walks through the common error types of a currency API, what each one means, and what your code should do. It ends with a compact JavaScript client you can adapt. The examples use the error codes of GetRatesAPI, but the grouping applies to any rate API.

Why generic error handling fails for currency data

A rate lookup usually sits in a critical path: a price on a product page, a total on an invoice, a balance in a dashboard. A failure there has a direct cost, so the response has to be deliberate.

Two common mistakes show up again and again:

  • Retrying everything. A malformed request will fail identically on the tenth attempt. A missing pair will not appear because you waited.
  • Retrying nothing. A brief 503 or a per-second limit is normal in any networked system. Failing the whole page for it is unnecessary.

The fix is to look at the machine-readable error code, not the HTTP status alone and not the message text. GetRatesAPI errors are JSON with code, message and request_id. Match on code only: messages are written for humans and can change. Keep request_id in your logs so you can point to the exact failed call if you ever contact support.

The three groups of errors

Here is how the documented error codes sort out. The full list is in the error reference.

CodeHTTPGroupWhat to do
invalid_asset_symbol400FixValidate the currency code before the call; do not retry
invalid_amount400FixValidate the amount string; do not retry
unauthorized401FixCheck the key and header; alert someone; do not retry
unsupported_pair404Tell the userHide or disable that currency; do not retry
rate_limit_exceeded429RetryWait retry_after_seconds, then try again
quota_exceeded429Tell the teamRetrying will not help; raise the plan or wait for the next period
temporarily_unavailable503RetryBack off with jitter, then fall back to a last known rate

Note that two codes share HTTP 429 but need opposite handling. That is the best argument for matching on code. A client that retries every 429 will keep retrying a quota_exceeded forever.

Errors you fix: 400 and 401

invalid_asset_symbol and invalid_amount mean the request itself was wrong: a typo like EURO, an empty string, or an amount such as 12,50 with a decimal comma. These are bugs or unvalidated input. Malformed requests are not billed, so they cost you no request units, but they still cost you a failed page.

Prevention beats handling here:

  • Populate currency pickers from the supported list instead of free text. The catalog endpoints (/v1/assets, /v1/assets/fiat, /v1/assets/crypto) are free and not billed, and the currencies page shows the same list.
  • Normalize amounts into a plain decimal string with a dot before sending them. Never send a float; keep money as strings, as covered in currency conversion rounding without floating-point errors.

unauthorized means the Authorization: ApiKey <key> header is missing, malformed, or the key was rotated or revoked in the dashboard. Retrying is pointless. Treat it as an operational alarm: log it loudly and notify the owner of the integration. A common cause is rotating a key and forgetting one deployment. See the authentication docs for the header format.

Errors you explain: unsupported_pair

unsupported_pair (404) means the service cannot produce a rate for that combination. GetRatesAPI derives missing pairs through USD, EUR or BTC, so this should be rare, but it can still happen with an asset that has no usable path. Do not retry. Decide what the product should do instead: hide that currency in the selector, fall back to the base currency, or show a clear message.

If you fetch several quotes in one call with GET /v1/rates/{base}?quote=EUR,GBP,JPY, an unsupported quote does not fail the call. It is listed in the unsupported field next to the rates you did get. Read that field, or you will silently drop currencies. More on batching in getting multiple exchange rates in one call.

Errors you retry: 429 rate limit and 503

rate_limit_exceeded means you exceeded the per-second limit of your plan. The error carries retry_after_seconds; wait that long and retry. Rate-limited requests are not billed. The full pattern, including queues and client-side throttling, is in handling API rate limits and retries.

temporarily_unavailable (503) is a transient server-side condition. Retry a small number of times with exponential backoff and random jitter, so many clients do not retry in lockstep. Then stop. Three attempts is plenty on a user-facing request.

quota_exceeded is different: your monthly request units are used up. You can check where you stand with GET /v1/account/usage, which returns the period, used, quota and remaining units. Do not retry in a loop. Alert the team, and consider the pricing page if usage has outgrown the plan. Better still, check usage on a schedule and warn before you hit zero, and use caching to reduce calls (see how to cache exchange rates without showing stale prices).

A small JavaScript client that applies the rules

This example uses Node.js 18+ and its built-in fetch. It reads the key from an environment variable, retries only the two retryable codes, and throws a typed error for everything else.

const BASE_URL = "https://api.getratesapi.com";
const API_KEY = process.env.GETRATES_API_KEY;

class RatesError extends Error {
  constructor(body, httpStatus) {
    super(body.message ?? "Rates request failed");
    this.code = body.code ?? "unknown";
    this.requestId = body.request_id;
    this.retryAfterSeconds = body.retry_after_seconds;
    this.httpStatus = httpStatus;
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function request(path) {
  const response = await fetch(`${BASE_URL}${path}`, {
    headers: { Authorization: `ApiKey ${API_KEY}` },
  });
  const body = await response.json().catch(() => ({}));
  if (!response.ok) throw new RatesError(body, response.status);
  return body;
}

async function getRate(base, quote, maxAttempts = 3) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await request(`/v1/rates/${base}/${quote}`);
    } catch (err) {
      const last = attempt >= maxAttempts;
      if (err.code === "rate_limit_exceeded" && !last) {
        await sleep((err.retryAfterSeconds ?? 1) * 1000);
      } else if (err.code === "temporarily_unavailable" && !last) {
        const backoff = 250 * 2 ** attempt;
        await sleep(backoff + Math.random() * backoff);
      } else {
        throw err; // fix-it and tell-the-user errors are never retried
      }
    }
  }
}

The caller then decides what each failure means for the product:

let lastGood = null; // e.g. loaded from your cache

async function priceInEur(usdAmount) {
  try {
    const rate = await getRate("USD", "EUR");
    lastGood = rate;
    return { rate, note: rate.status === "stale" ? "rate may be outdated" : null };
  } catch (err) {
    console.error("rates error", err.code, err.requestId);
    switch (err.code) {
      case "unsupported_pair":
        return { hidden: true }; // do not offer this currency
      case "temporarily_unavailable":
      case "rate_limit_exceeded":
        if (lastGood) return { rate: lastGood, note: `rate as of ${lastGood.as_of}` };
        throw err;
      default:
        throw err; // unauthorized, invalid_*, quota_exceeded: alert, do not mask
    }
  }
}

Two details matter here. First, the fallback shows the original as_of timestamp, so the user sees how old the number is. Second, unauthorized, invalid_* and quota_exceeded are not masked by a fallback, because hiding them would let a broken key or an exhausted quota go unnoticed for days.

Success responses need handling too

A 200 response is not automatically a usable one. Every rate carries status, either fresh or stale. Stale rates are flagged, not withheld, so the API will still give you a number when the underlying observation is old (more than 1 minute for crypto, 5 minutes for fiat). Your code decides whether that is acceptable: fine for a product listing, perhaps not for locking a payment quote.

Also check type. A derived rate is built from other rates, and its as_of is the oldest of its inputs. That is useful to know when you display or store a timestamp for audit purposes.

A short checklist

  • Match on code, never on message text or HTTP status alone.
  • Retry only rate_limit_exceeded and temporarily_unavailable, with a hard attempt limit.
  • Validate currency codes and amounts before sending.
  • Log request_id with every failure.
  • Alert on unauthorized and quota_exceeded; do not retry them.
  • Read the unsupported list on multi-quote calls.
  • Check status and as_of on successful responses.

Try it against a real key

The fastest way to see each behavior is to trigger it. Sign up for the free plan (no credit card), open the dashboard playground, and send a bad symbol or amount to see the JSON error shape. Then wire the client above into your app and read the REST error docs for the complete list of codes.

All articles →
Exchange Rate API Error Handling: Codes and Fixes — GetRatesAPI