How to handle exchange rate API errors and rate limits? #10
-
|
What errors can the API return and how should I handle rate limiting in production? AnswerError codes:
JavaScript error handling: import { ExchangeRateAPI, ExchangeRateAPIError } from '@exchangerateapi/sdk';
const client = new ExchangeRateAPI({ apiKey: 'era_live_YOUR_KEY' });
try {
const data = await client.latest();
} catch (err) {
if (err instanceof ExchangeRateAPIError) {
if (err.status === 429) {
console.log('Rate limited, using cache');
} else {
console.error(`API error: ${err.message} (${err.status})`);
}
}
}Python error handling: from exchangerateapi import ExchangeRateAPI, ExchangeRateAPIError
client = ExchangeRateAPI(api_key="era_live_YOUR_KEY")
try:
data = client.latest()
except ExchangeRateAPIError as e:
print(f"Error: {e} (status: {e.status})")Best practice: Cache rates Exchange rates don't change every second. Cache responses for 60 seconds to minimize API calls: let cache = { data: null, timestamp: 0 };
async function getRates() {
const now = Date.now();
if (cache.data && now - cache.timestamp < 60000) {
return cache.data;
}
const data = await client.latest({ base: 'USD' });
cache = { data, timestamp: now };
return data;
}This reduces your API usage dramatically while still serving fresh data. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Error codes:
JavaScript error handling: import { ExchangeRateAPI, ExchangeRateAPIError } from '@exchangerateapi/sdk';
const client = new ExchangeRateAPI({ apiKey: 'era_live_YOUR_KEY' });
try {
const data = await client.latest();
} catch (err) {
if (err instanceof ExchangeRateAPIError) {
if (err.status === 429) {
console.log('Rate limited, using cache');
} else {
console.error(`API error: ${err.message} (${err.status})`);
}
}
}Python error handling: from exchangerateapi import ExchangeRateAPI, ExchangeRateAPIError
client = ExchangeRateAPI(api_key="era_live_YOUR_KEY")
try:
data = client.latest()
except ExchangeRateAPIError as e:
print(f"Error: {e} (status: {e.status})")Best practice: Cache rates Exchange rates don't change every second. Cache responses for 60 seconds to minimize API calls: let cache = { data: null, timestamp: 0 };
async function getRates() {
const now = Date.now();
if (cache.data && now - cache.timestamp < 60000) {
return cache.data;
}
const data = await client.latest({ base: 'USD' });
cache = { data, timestamp: now };
return data;
}This reduces your API usage dramatically while still serving fresh data. |
Beta Was this translation helpful? Give feedback.
Error codes:
JavaScript error handling: