Bỏ qua, tới nội dung chính
Fleetwork
Fleetwork

Liên hệ

Chúng tôi rất mong nhận được liên hệ từ bạn. Vui lòng điền vào biểu mẫu bên dưới.

APITham khảo

Xử lý lỗi

Các mẫu xử lý lỗi và chiến lược retry cho Fleetwork API bằng JavaScript.

Lớp xử lý lỗi

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

      // Bị giới hạn tốc độ — thử lại sau khoảng chờ
      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");
  }

  // Các phương thức tiện lợi
  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;
  }
}

Cách sử dụng

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