Error Handling
Error handling patterns and retry strategies for the Fleetwork API in JavaScript.
Error Handler Class
class FleetworkApiClient {
constructor(apiKey, baseUrl = "https://live.fleetwork.vn") {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
async request(method, path, { body, params } = {}) {
const url = new URL(`${this.baseUrl}/api/v1/workspace/accounts${path}`);
if (params) {
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
}
const options = {
method,
headers: {
"API-KEY": this.apiKey,
"Content-Type": "application/json",
},
};
if (body) options.body = JSON.stringify(body);
for (let attempt = 0; attempt < 3; attempt++) {
const response = await fetch(url, options);
// Rate limited — retry after delay
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get("Retry-After") || "1");
console.warn(`Rate limited. Retrying in ${retryAfter}s...`);
await new Promise((r) => setTimeout(r, retryAfter * 1000));
continue;
}
const data = await response.json();
if (!response.ok) {
throw new FleetworkApiError(response.status, data);
}
return data;
}
throw new Error("Max retries exceeded");
}
// Convenience methods
get(path, params) {
return this.request("GET", path, { params });
}
post(path, body) {
return this.request("POST", path, { body });
}
put(path, body) {
return this.request("PUT", path, { body });
}
delete(path) {
return this.request("DELETE", path);
}
}
class FleetworkApiError extends Error {
constructor(statusCode, body) {
super(body.message || body.error || "Unknown API error");
this.statusCode = statusCode;
this.body = body;
}
}Usage
const client = new FleetworkApiClient("your-key", "your-account-id");
try {
const users = await client.get("/users", { page: "1", size: "20" });
console.log(users.data.content);
} catch (error) {
if (error instanceof FleetworkApiError) {
switch (error.statusCode) {
case 401:
console.error("Auth failed:", error.message);
break;
case 404:
console.error("Not found:", error.message);
break;
case 429:
console.error("Rate limited");
break;
default:
console.error(`API Error ${error.statusCode}:`, error.message);
}
}
}