Thuta Learning
API Tutorial
ProjectsWeb Developmentအလယ်အလတ်

Mini Project — Part 3: Error Handling နဲ့ Polish

API Tutorialသင်ခန်းစာ 3145 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • AbortSignal.timeout နဲ့ attempt တစ်ခုချင်းစီအတွက် timeout ထည့်ပြီး အဲဒါကြောင့်ဖြစ်တဲ့ TimeoutError ကို သိနိုင်ဖို့
  • Transient failure တွေကို Retry-After ကို လေးစားပြီး exponential backoff နဲ့ ပြန်ကြိုးစားနိုင်ဖို့၊ ဘယ် method ကို ပြန်ပို့လို့ ဘေးကင်းလဲ ဆုံးဖြတ်နိုင်ဖို့
  • Failure တွေကို http, network, timeout, parse အဖြစ် ခွဲပြီး caller တွေက တစ်ခုချင်းစီကို မတူအောင် တုံ့ပြန်နိုင်ဖို့
  • List တစ်ခုရဲ့ page အားလုံးကို async generator နဲ့ လျှောက်ဖတ်နိုင်ဖို့
  • CLI crash မဖြစ်စေဘဲ typed result နဲ့ ဖော်ရွေတဲ့ message ပြန်ပေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Part 1 နဲ့ Part 2 က ကောင်းတဲ့နေ့မှာ အလုပ်လုပ်ပါတယ်။ Part 3 က တခြားနေ့တွေအကြောင်းပါ၊ server နှေးတာ၊ Wi-Fi ပြတ်တာ၊ provider က 429 ပြန်တာ၊ ဒါမှမဟုတ် proxy က HTML error page ပြန်ပို့တာတွေပါ။ ဒီမှာ feature အသစ် ဘာမှမထည့်ပါဘူး၊ ရှိပြီးသား feature တွေ ပြဿနာတက်ချိန် ကောင်းကောင်းလုပ်နိုင်အောင်သာ လုပ်ပါတယ်။

ကြိုဆက်ပြီး ဖုန်းဆက်၊ တံခါးဝမှာ သင့်တော်တဲ့ အချိန်စောင့်၊ ပို့တာမအောင်မြင်ရင် နောက်နေ့ ထပ်ကြိုးစား၊ ဒါပေမယ့် ပါဆယ်တူတူကို နှစ်ကြိမ် ဘယ်တော့မှ မပို့ဘဲ လက်လျှော့ရင် ရှင်းတဲ့ မှတ်စုချန်ခဲ့တဲ့ courier တစ်ယောက်ကို စဉ်းစားကြည့်ပါ။ အဲဒီ courier က သင် အခု အပြီးသတ်မယ့် client ပါ။

Problem → Why → Solution

ပြဿနာ: ပျက်ကွက်မှုအပေါ် ထင်မြင်ချက်မရှိတဲ့ client

Part 2 client မှာ failure အပေါ် ထင်မြင်ချက် မရှိပါဘူး။ Server က လုံးဝ မဖြေရင် fetch က အချိန်အရမ်းကြာကြာ စောင့်ပြီး command က ရပ်နေပါတယ်။ တစ်စက္ကန့်ကြာရင် ပြေလည်သွားမယ့် 503 တစ်ခုက command တစ်ခုလုံးကို အဆုံးသတ်ပါတယ်။ Proxy က status 200 နဲ့ HTML page ပြန်လာရင် res.json() က angle bracket အကြောင်း SyntaxError နဲ့ ပျက်ပြီး တကယ့်အကြောင်းရင်းကို ဘာမှ မပြောပါဘူး။

ဆန့်ကျင်ဘက် စိတ်ဓာတ်ကလည်း အန္တရာယ်တူပါတယ်။ Error မှန်သမျှမှာ ပြန်ကြိုးစားတဲ့ loop ထဲ call တိုင်းကို ထည့်တာက လုံခြုံသလိုထင်ရပေမယ့် user တူတူကို သုံးကြိမ် ဖန်တီးမိနိုင်ပြီး ရုန်းကန်နေတဲ့ server ကို သက်သာမှု အလိုအပ်ဆုံးအချိန်မှာ ထပ်ထိုးနှက်ပါတယ်။

draft.js
// A tempting but dangerous retry loop
async function withRetry(fn) {
  for (let i = 0; i < 3; i++) {
    try {
      return await fn();
    } catch {
      // try again immediately, whatever went wrong
    }
  }
}

await withRetry(() => client.createUser(input)); // may create the same user three times

အားလုံးကို ဘာကြောင့် ပြန်မကြိုးစားတာလဲ

Request ကို ထပ်ပို့တာ ဘေးကင်းမှသာ retry က အခွင့်အရေးဒုတိယတစ်ခု ဖြစ်ပါတယ်။ GET ကို ထပ်ပို့ရင် ဘာမှမပြောင်းပေမယ့် server က လုပ်ပြီးသား POST ကို ထပ်ပို့ရင် duplicate ဖြစ်ပြီး ချက်ချင်း ပြန်ကြိုးစားရင် overload ဖြစ်နေတဲ့ server ကို သက်သာဖို့ လိုအပ်ချိန်မှာ load ပိုပေးရာ ရောက်ပါတယ်။ ဒါကြောင့် ကောင်းတဲ့ policy က ရွေးချယ်တတ်ရမယ် (ဘယ် failure၊ ဘယ် method)၊ သည်းခံတတ်ရမယ် (backoff) နဲ့ အတိုင်းအတာရှိရမယ် (အများဆုံးအကြိမ်ရေ) ပါ။

Core concept: မြန်မြန်ရပ်၊ သတိနဲ့ပြန်ကြိုးစား၊ ရှင်းရှင်းပြော

Client ကို ကျန်းမာစေတဲ့ ယန္တရားသုံးခု သီးခြားရှိပါတယ်။ Timeout က စောင့်ရမယ့်အချိန်ကို ကန့်သတ်ပါတယ်၊ AbortSignal.timeout(ms) က delay ပြီးရင် abort ဖြစ်မယ့် signal ကို ပြန်ပေးပြီး fetch ကို signal အဖြစ် ပေးလိုက်ရင် request က TimeoutError နဲ့ reject ဖြစ်ပါတယ်။ Attempt တိုင်းအတွက် signal အသစ်ကို ဖန်တီးပါ၊ ဘာလို့လဲဆိုတော့ signal တစ်ခုက deadline တစ်ခုကို ကိုယ်စားပြုပြီး reset မလုပ်နိုင်လို့ပါ။ Retry policy က ဘယ် failure တွေ နောက်တစ်ကြိမ်ထိုက်တန်လဲ၊ ဘယ်လောက်ရပ်နားမလဲ ဆုံးဖြတ်ပါတယ်။ ပြီးတော့ error taxonomy က CLI နောက်က code ကို ပယ်ချခံရတဲ့ request၊ သေနေတဲ့ network နဲ့ နှေးတဲ့ server တို့ကို မတူအောင် တုံ့ပြန်ခွင့်ပေးပါတယ်။

၁။ Failure ကို ခွဲခြားပါ

attemptOnce() က မှားနိုင်သမျှအားလုံးကို kind ပါတဲ့ ApiError တစ်ခုအဖြစ် ပြောင်းပါတယ်၊ network က response မရောက်တာ (တကယ့်အကြောင်းရင်းက ECONNREFUSED လို err.cause.code ထဲမှာ)၊ timeout၊ parse က 2xx body က JSON မဟုတ်တာ၊ ကျန်တာက http ပါ။

၂။ ပြန်ကြိုးစားတာ ဘေးကင်းလားဆုံးဖြတ်ပါ

429 ကို အမြဲ ပြန်ကြိုးစားလို့ရပါတယ်၊ server က အလုပ်ကို ပယ်ချခဲ့လို့ပါ။ Network error၊ timeout နဲ့ 502, 503, 504 ကိုတော့ idempotent method (GET, HEAD, PUT, DELETE) တွေအတွက်ပဲ ပြန်ကြိုးစားပါတယ်။ POST နဲ့ PATCH ကို အလိုအလျောက် ဘယ်တော့မှ ပြန်မပို့ပါဘူး။

၃။ စောင့်ပြီးမှ ထပ်ကြိုးစားပါ

Server က Retry-After ပို့ရင် အဲဒါကို သုံးပါ။ မဟုတ်ရင် baseDelay x 2 ရဲ့ (attempt - 1) ထပ်ကိန်း ကို စောင့်ပြီး အများဆုံးတန်ဖိုးနဲ့ ကန့်သတ်ကာ jitter နဲ့ random လုပ်ရင် ကောင်းပါတယ်၊ ဒါမှ client အများကြီး တစ်ပြိုင်တည်း ပြန်မကြိုးစားမှာပါ။ ခွင့်ပြုထားတဲ့ နောက်ဆုံး retry ပြီးရင် error ကို ပြန် throw လုပ်ပါ။

သေးငယ်တဲ့ idea နှစ်ခုက အလုပ်ကို အပြီးသတ်ပါတယ်။ Async generator အဖြစ်ရေးထားတဲ့ pagination iterator (async *iterateUsers) က page တစ်ခုပြီးတစ်ခု တောင်းပြီး user တစ်ယောက်ချင်း yield လုပ်လို့ caller က for await (const user of client.iterateUsers()) လို့ရေးပြီး page ကို ရေတွက်စရာ မလိုပါဘူး။ ပြီးတော့ { ok: true, value } ဒါမှမဟုတ် { ok: false, error } ဆိုတဲ့ result type က CLI ကို result.ok ပေါ်မှာ တစ်နေရာတည်း ခွဲပြီး friendlyMessage(error) ကို print လုပ်ခွင့်ပေးလို့ user က stack trace အစား 'That token looks wrong' ကို ဖတ်ရပါတယ်။

Failureပြန်ကြိုးစားမလားအကြောင်းရင်း
429 Too Many Requestsဟုတ်၊ Retry-After ပြီးမှServer က ပယ်ချခဲ့ပြီး ဘာမှ မလုပ်ရသေး
502/503/504၊ timeout၊ network ပြတ် (GET/PUT/DELETE)ဟုတ်၊ backoff နဲ့ထပ်ပို့ရင် ဘာမှမပြောင်း
POST/PATCH မှာ အဲဒီ failure တွေတူတူမလုပ်ဘူးServer က လုပ်ပြီးသားဖြစ်နိုင်
400/401/404/409/422၊ JSON ပျက်မလုပ်ဘူးထပ်ပို့ရင် အဖြေတူတူပဲ ရမယ်
Mental model: attempt တစ်ခု၊ ဆုံးဖြတ်ချက်တစ်ခု
  1. ဒီ attempt အတွက် timeout အသစ်စ
  2. ရလဒ်ကို ApiError ဒါမှမဟုတ် data ပြောင်း
  3. ဘေးကင်းတာကိုပဲ ခဏစောင့်ပြီး ပြန်ကြိုးစား
  4. ကန့်သတ်ချက်ပြည့်ရင် ပီပြင်စွာ လက်လျှော့

Request ကို ထပ်ပို့တာ ဘေးကင်းမှသာ retry က အခွင့်အရေးဒုတိယတစ်ခုပါ၊ ကျန်တာအားလုံးကို ချက်ချင်းနဲ့ ရှင်းရှင်းပြောပါ။

အခြေခံ ပုံစံ

javascript
for (let attempt = 1; ; attempt++) {
  try {
    return await attemptOnce(); // fresh AbortSignal.timeout(ms) created inside
  } catch (err) {
    if (!isSafeToRetry(err) || attempt > maxRetries) throw err;
    await sleep(retryAfter ?? Math.min(cap, base * 2 ** (attempt - 1)));
  }
}

Retry loop တစ်ခုပါ။ attempt တိုင်းက timeout အသစ်ပါပြီး မအောင်မြင်ရင် ဘေးကင်းလားစစ်၊ ကန့်သတ်ချက်ထက် မကျော်ရင် server ရဲ့ hint ဒါမှမဟုတ် ကိန်းနှစ်ထပ်တိုးတဲ့ delay ကို စောင့်ပါတယ်။

Part 3 code: timeout, retry, error kind, pagination နဲ့ help command

ဒါက Part 3 ရဲ့ file အပြည့်အစုံပါ။ Part 2 က mock API ကို ထပ်ထည့်ထားလို့ ရှည်ပါတယ်၊ ဒီတစ်ခါတော့ fault queue ပါပါတယ်။ Fault တစ်ခုကို push လုပ်ရင် နောက်လာမယ့် request တစ်ခုကို အတိအကျ ပျက်စေပြီး အဲဒါကြောင့် retry စည်းမျဉ်းတိုင်းကို test လုပ်လို့ရပါတယ်။ Client ကို အရင်ဖတ်ပြီး အောက်ဆုံးက နံပါတ်စဉ် demo scenario ရှစ်ခုကို ဖတ်ပါ။

Demo က sleep ကို တောင်းဆိုခံရတဲ့ delay ကိုပဲ မှတ်တမ်းတင်တဲ့ function နဲ့ အစားထိုးထားလို့ တကယ်မစောင့်ဘဲ run တိုင်း output တူပါတယ်။ Production မှာတော့ sleep ကို မထိဘဲ jitter ကို ဖွင့်ထားပြီး timeout ကို အနှေးဆုံး ကျန်းမာတဲ့ request အတွက် လုံလောက်အောင် ကြီးကြီးထားပါ။

part3.mjs
// user-cli, part 3: timeouts, retries with backoff, error kinds, pagination, help.
// Save as part3.mjs and run: node part3.mjs   (Node 20.12 or newer)
// Lines marked NEW (or between ">>> NEW" and "<<< end") were added in this part.
import http from "node:http";

// ===== 1. Mock API: now with injectable faults =====
const TOKEN = "demo-token-123";
const users = [
  { id: "u_1", name: "Alice", email: "alice@example.com" },
  { id: "u_2", name: "Bob", email: "bob@example.com" },
  { id: "u_3", name: "Chidi", email: "chidi@example.com" },
  { id: "u_4", name: "Dara", email: "dara@example.com" },
  { id: "u_5", name: "Eli", email: "eli@example.com" },
];
let nextId = 6;
const faults = []; // NEW: each queued fault spoils exactly one upcoming request
let served = 0; // NEW: how many requests reached the server

function send(res, status, body, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
}
function fail(res, status, code, message, fields) {
  send(res, status, { error: { code, message, ...(fields && { fields }) } });
}
async function readJson(req) {
  let raw = "";
  for await (const chunk of req) raw += chunk;
  return raw ? JSON.parse(raw) : {};
}
function validate(input, partial) {
  const fields = {};
  if (!partial || "name" in input) {
    if (typeof input.name !== "string" || !input.name.trim()) fields.name = "required";
  }
  if (!partial || "email" in input) {
    if (typeof input.email !== "string" || !/^[^@\s]+@[^@\s]+$/.test(input.email)) {
      fields.email = "invalid";
    }
  }
  return fields;
}

// >>> NEW in part 3: misbehave on purpose when a fault is queued
function injectFault(fault, res) {
  if (fault === "garbled") { // a proxy error page sent with a JSON content type
    res.writeHead(200, { "Content-Type": "application/json" });
    return res.end("<html>Bad gateway page</html>");
  }
  if (fault === "slow") return; // never answers; the client gives up and closes
  const { status, code, message, retryAfter } = fault;
  const headers = retryAfter ? { "Retry-After": String(retryAfter) } : {};
  send(res, status, { error: { code, message } }, headers);
}
// <<< end of injectFault

const mock = http.createServer(async (req, res) => {
  served++; // NEW
  if (req.headers.authorization !== `Bearer ${TOKEN}`) {
    return fail(res, 401, "UNAUTHORIZED", "Missing or invalid token");
  }
  if (faults.length) return injectFault(faults.shift(), res); // NEW
  const url = new URL(req.url, "http://mock");
  const one = url.pathname.match(/^\/v1\/users\/([\w-]+)$/);
  const found = one && users.find((u) => u.id === one[1]);
  try {
    if (req.method === "GET" && url.pathname === "/v1/users") {
      const page = Number(url.searchParams.get("page") ?? 1);
      const limit = Number(url.searchParams.get("limit") ?? 10);
      const data = users.slice((page - 1) * limit, page * limit);
      return send(res, 200, { data, meta: { page, limit, total: users.length } });
    }
    if (req.method === "POST" && url.pathname === "/v1/users") {
      const input = await readJson(req);
      const fields = validate(input, false);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (users.some((u) => u.email === input.email)) {
        return fail(res, 409, "CONFLICT", "Email already in use");
      }
      const user = { id: `u_${nextId++}`, name: input.name.trim(), email: input.email };
      users.push(user);
      return send(res, 201, { data: user });
    }
    if (one && !found) return fail(res, 404, "NOT_FOUND", `User ${one[1]} not found`);
    if (req.method === "GET" && found) return send(res, 200, { data: found });
    if (req.method === "PATCH" && found) {
      const changes = await readJson(req);
      const fields = validate(changes, true);
      if (Object.keys(fields).length) {
        return fail(res, 422, "VALIDATION_ERROR", "Invalid user data", fields);
      }
      if (changes.name) found.name = changes.name.trim();
      if (changes.email) found.email = changes.email;
      return send(res, 200, { data: found });
    }
    if (req.method === "DELETE" && found) {
      users.splice(users.indexOf(found), 1);
      res.writeHead(204);
      return res.end();
    }
    fail(res, 404, "NOT_FOUND", "No such route");
  } catch (err) {
    if (err instanceof SyntaxError) {
      return fail(res, 400, "INVALID_JSON", "Body is not JSON");
    }
    fail(res, 500, "INTERNAL", "Unexpected server error");
  }
});

// ===== 2. The client library =====
class ApiError extends Error {
  constructor(status, code, message, extra = {}) {
    super(message, { cause: extra.cause }); // NEW: keep the low-level error
    this.name = "ApiError";
    this.status = status; // NEW: 0 means no HTTP response arrived at all
    this.code = code;
    this.fields = extra.fields;
    this.kind = extra.kind ?? "http"; // NEW: "http" | "network" | "timeout" | "parse"
    this.retryAfterMs = extra.retryAfterMs; // NEW
  }
}

function loadConfig(env = process.env) {
  const token = env.API_TOKEN;
  if (!token) throw new Error("API_TOKEN is not set (put it in .env, never in code)");
  return { baseUrl: env.API_BASE_URL ?? "https://api.example.com/v1", token };
}

// >>> NEW in part 3: retry policy helpers
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE"]);
const TRANSIENT = new Set([502, 503, 504]);

function parseRetryAfter(value, now = Date.now()) {
  if (!value) return undefined;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000; // seconds
  const when = Date.parse(value); // or an HTTP date
  return Number.isNaN(when) ? undefined : Math.max(0, when - now);
}

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

function fetchFailure(err, timeoutMs) {
  if (err.name === "TimeoutError") {
    const message = `No answer within ${timeoutMs}ms`;
    return new ApiError(0, "TIMEOUT", message, { kind: "timeout", cause: err });
  }
  const code = err.cause?.code ?? "NETWORK_ERROR"; // e.g. ECONNREFUSED
  const message = "Could not reach the server";
  return new ApiError(0, code, message, { kind: "network", cause: err });
}

function backoffDelay(attempt, { baseDelayMs, maxDelayMs, jitter }) {
  const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
  return jitter ? Math.round(Math.random() * ceiling) : ceiling;
}

function shouldRetry(method, err) {
  if (err.status === 429) return true; // the server refused it, so replay is safe
  if (!IDEMPOTENT.has(method)) return false; // never replay a POST blindly
  return err.kind === "network" || err.kind === "timeout" || TRANSIENT.has(err.status);
}
// <<< end of retry policy helpers

function createClient(options) {
  const { baseUrl, token } = options;
  const { timeoutMs = 5000, retries = 3, baseDelayMs = 200, maxDelayMs = 5000 } = options;
  const { jitter = true, onRetry = () => {} } = options;
  const sleep = options.sleep ?? wait;

  // NEW: one attempt = one fresh timeout signal, and every failure becomes an ApiError
  async function attemptOnce(method, route, body) {
    const headers = {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
      "Accept-Version": "v1", // NEW: pin the API version (header style)
    };
    if (body !== undefined) headers["Content-Type"] = "application/json";
    let res, text;
    try {
      res = await fetch(`${baseUrl}${route}`, {
        method,
        headers,
        body: body === undefined ? undefined : JSON.stringify(body),
        signal: AbortSignal.timeout(timeoutMs),
      });
      text = res.status === 204 ? "" : await res.text();
    } catch (err) {
      throw fetchFailure(err, timeoutMs);
    }
    if (res.status === 204) return null;
    const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"));
    let payload;
    try {
      payload = JSON.parse(text);
    } catch {
      if (!res.ok) {
        const msg = `Server answered ${res.status} without a JSON body`;
        throw new ApiError(res.status, `HTTP_${res.status}`, msg, { retryAfterMs });
      }
      const message = "Response body is not valid JSON";
      throw new ApiError(res.status, "BAD_JSON", message, { kind: "parse" });
    }
    if (!res.ok) {
      const e = payload.error ?? {};
      const code = e.code ?? `HTTP_${res.status}`;
      throw new ApiError(res.status, code, e.message ?? res.statusText, {
        fields: e.fields,
        retryAfterMs,
      });
    }
    return payload;
  }

  // NEW: request() keeps its signature, but now it retries what is safe to retry
  async function request(method, route, body) {
    for (let attempt = 1; ; attempt++) {
      try {
        return await attemptOnce(method, route, body);
      } catch (err) {
        const retryable = err instanceof ApiError && shouldRetry(method, err);
        if (!retryable || attempt > retries) throw err;
        const policy = { baseDelayMs, maxDelayMs, jitter };
        const delay = err.retryAfterMs ?? backoffDelay(attempt, policy);
        if (delay > maxDelayMs) throw err; // the server wants longer than we will wait
        onRetry({ attempt, retries, delay, error: err });
        await sleep(delay);
      }
    }
  }

  const userPath = (id) => `/users/${encodeURIComponent(id)}`;
  const client = {
    listUsers({ page = 1, limit = 10 } = {}) {
      return request("GET", `/users?page=${page}&limit=${limit}`);
    },
    async getUser(id) {
      return (await request("GET", userPath(id))).data;
    },
    async createUser(input) {
      return (await request("POST", "/users", input)).data;
    },
    async updateUser(id, changes) {
      return (await request("PATCH", userPath(id), changes)).data;
    },
    async deleteUser(id) {
      await request("DELETE", userPath(id));
    },
    // >>> NEW in part 3: walk every page without the caller counting pages
    async *iterateUsers({ pageSize = 2 } = {}) {
      for (let page = 1; ; page++) {
        const { data, meta } = await client.listUsers({ page, limit: pageSize });
        yield* data;
        if (data.length === 0 || page * pageSize >= meta.total) return;
      }
    },
    // <<< end new
  };
  return client;
}

// >>> NEW in part 3: typed results and human-readable messages
/** @typedef {{ ok: true, value: any } | { ok: false, error: ApiError }} Result */
/** @returns {Promise<Result>} */
async function toResult(fn) {
  try {
    return { ok: true, value: await fn() };
  } catch (error) {
    if (error instanceof ApiError) return { ok: false, error };
    throw error; // a bug in our own code should stay loud
  }
}

function friendlyMessage(err) {
  if (err.kind === "timeout") return "The server took too long to answer.";
  if (err.kind === "network") return `Cannot reach the server (${err.code}).`;
  if (err.kind === "parse") return "The server replied with something that is not JSON.";
  switch (err.status) {
    case 401: return "That token looks wrong - please double-check it.";
    case 404: return "Nothing exists with that id.";
    case 409: return "That email is already taken.";
    case 422: return `Please fix: ${Object.keys(err.fields ?? {}).join(", ")}.`;
    case 429: return "Rate limited. Wait a little, then try again.";
    default: return `Request failed (${err.status} ${err.code}).`;
  }
}

const USAGE = [
  "usage: user-cli <command>",
  "  list                       show the first page of users",
  "  get <id>                   show one user",
  "  create <name> <email>      add a user",
  "  update <id> key=value...   change name and/or email",
  "  delete <id>                remove a user",
].join("\n");
// <<< end of results and messages

function parsePairs(pairs) {
  const changes = {};
  for (const pair of pairs) {
    const i = pair.indexOf("=");
    if (i < 1) throw new Error(`expected key=value, got "${pair}"`);
    changes[pair.slice(0, i)] = pair.slice(i + 1);
  }
  return changes;
}

const show = (u) => `${u.id}: ${u.name} <${u.email}>`;

// NEW: runCommand returns { ok, text } so main() can set the exit code once
async function runCommand(client, argv) {
  const [cmd, ...args] = argv;
  const commands = {
    list: async () => {
      const { data, meta } = await client.listUsers();
      return `${data.map((u) => u.name).join(", ")} (${meta.total} total)`;
    },
    get: async () => show(await client.getUser(args[0])),
    create: async () => {
      const user = await client.createUser({ name: args[0], email: args[1] });
      return `created ${show(user)}`;
    },
    update: async () => {
      const user = await client.updateUser(args[0], parsePairs(args.slice(1)));
      return `updated ${show(user)}`;
    },
    delete: async () => {
      await client.deleteUser(args[0]);
      return `deleted ${args[0]}`;
    },
  };
  if (!commands[cmd]) return { ok: false, text: USAGE };
  const result = await toResult(commands[cmd]);
  if (result.ok) return { ok: true, text: result.value };
  return { ok: false, text: friendlyMessage(result.error) };
}
// A real cli.js would end with:
//   const r = await runCommand(client, process.argv.slice(2));
//   console.log(r.text); process.exitCode = r.ok ? 0 : 1;

// ===== 3. Demo: every scenario below is deterministic =====
await new Promise((resolve) => mock.listen(0, "127.0.0.1", resolve));
try {
  const { port } = mock.address();
  const baseUrl = `http://127.0.0.1:${port}/v1`;
  const waits = [];
  const fast = {
    baseUrl, token: TOKEN, timeoutMs: 300, baseDelayMs: 20, jitter: false,
    sleep: async (ms) => { waits.push(ms); }, // do not really sleep in a demo
    onRetry: ({ attempt, retries, delay, error }) =>
      console.log(`  retry ${attempt}/${retries} in ${delay}ms after ${error.code}`),
  };
  const client = createClient(fast);
  const unavailable = { status: 503, code: "UNAVAILABLE", message: "Try later" };

  console.log("1. two 503s, then success (GET is safe to replay)");
  faults.push(unavailable, unavailable);
  console.log("  ->", (await client.getUser("u_1")).name, `after ${served} requests`);

  console.log("2. 429 with Retry-After: 1 beats our own backoff");
  faults.push({ status: 429, code: "RATE_LIMITED", message: "Slow down", retryAfter: 1 });
  console.log("  ->", (await client.getUser("u_2")).name);

  console.log("3. a 503 on POST is not replayed");
  served = 0;
  faults.push(unavailable);
  const gus = { name: "Gus", email: "gus@example.com" };
  const created = await toResult(() => client.createUser(gus));
  console.log("  ->", created.error.status, `after ${served} request`);

  console.log("4. a slow server hits the per-attempt timeout, then recovers");
  faults.push("slow");
  console.log("  ->", (await client.getUser("u_3")).name);

  console.log("5. malformed JSON is a parse error, not retried");
  faults.push("garbled");
  const garbled = await toResult(() => client.getUser("u_1"));
  console.log("  ->", garbled.error.kind, "|", friendlyMessage(garbled.error));

  console.log("6. nothing is listening on the port");
  const closed = http.createServer();
  await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
  const deadUrl = `http://127.0.0.1:${closed.address().port}/v1`;
  await new Promise((resolve) => closed.close(resolve));
  const offline = createClient({ ...fast, baseUrl: deadUrl, retries: 1 });
  const down = await toResult(() => offline.listUsers());
  console.log("  ->", down.error.kind, down.error.code, "|", friendlyMessage(down.error));

  console.log("7. the iterator hides the paging");
  served = 0;
  const names = [];
  for await (const user of client.iterateUsers({ pageSize: 2 })) names.push(user.name);
  console.log("  ->", names.join(", "), `(${served} requests)`);

  console.log("8. the CLI turns every failure into a sentence");
  const wrong = createClient({ ...fast, token: "nope" });
  const attempts = [[client, ["get", "u_99"]], [wrong, ["list"]], [client, ["help"]]];
  for (const [who, argv] of attempts) {
    const out = await runCommand(who, argv);
    console.log("  ->", out.ok ? "ok" : "fail", "|", out.text.split("\n")[0]);
  }
  console.log("sleeps requested:", waits.join(", "));
} finally {
  mock.close();
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Fresh deadline per attemptsignal: AbortSignal.timeout(timeoutMs),

    attemptOnce() ကို ခေါ်တိုင်း signal အသစ်ကို ဖန်တီးပါတယ်။ ဒါကြောင့် ပထမ attempt timeout ဖြစ်ပြီးနောက်လည်း ဒုတိယ attempt က ကိုယ်ပိုင် deadline အပြည့်ရပါတယ်။

  2. Read the real network codeconst code = err.cause?.code ?? "NETWORK_ERROR"; // e.g. ECONNREFUSED

    fetch ရဲ့ network failure က message က fetch failed ပဲပါတဲ့ TypeError ပါ။ အသုံးဝင်တဲ့ code က err.cause ထဲမှာ ရှိလို့ အဲဒါကို ဆွဲထုတ်ပြီး ApiError ရဲ့ code အဖြစ် သုံးပါတယ်။

  3. Method decides replay safetyif (!IDEMPOTENT.has(method)) return false; // never replay a POST blindly

    429 ကို ကျော်လွန်ပြီးနောက် ဒီ line က POST နဲ့ PATCH ကို ပြန်ကြိုးစားခြင်းကနေ ထုတ်ပစ်ပါတယ်။ ဒါကြောင့် 503 ပြန်လာတဲ့ create က duplicate user မဖြစ်စေပါဘူး။

  4. Retry-After beats our guessconst delay = err.retryAfterMs ?? backoffDelay(attempt, policy);

    Server က ဘယ်လောက်စောင့်ရမလဲ ပြောထားရင် အဲဒါက client ရဲ့ ခန့်မှန်းချက်ထက် ပိုမှန်ပါတယ်။ မပြောရင်တော့ exponential backoff ကို ပြန်သုံးပါတယ်။

  5. Yield users, not pagesyield* data;

    iterateUsers() က page တစ်ခုချင်းစီရဲ့ user တွေကို တစ်ယောက်ချင်း ထုတ်ပေးပါတယ်။ Caller က for await နဲ့ ဖတ်ရုံပဲ၊ page နံပါတ်၊ limit၊ total ကို မတွက်ရပါဘူး။

  6. A typed resultif (error instanceof ApiError) return { ok: false, error };

    ApiError ကိုသာ ok: false result အဖြစ် ပြောင်းပါတယ်။ ကိုယ့် code ထဲက bug က ဆက် throw ဖြစ်ပြီး ဖုံးကွယ်မခံရလို့ အမှားတွေ ပီပြင်နေပါတယ်။

  7. Fault injection makes retries testablefaults.push(unavailable, unavailable);

    Mock ကို နောက်လာမယ့် request နှစ်ခုကို 503 နဲ့ ဖြေခိုင်းလိုက်တာပါ။ ဒါဆို တကယ့် server က မတည်ငြိမ်တာကို မစောင့်ဘဲ retry logic ကို တိကျစွာ စမ်းနိုင်ပါတယ်။

You should see
1. two 503s, then success (GET is safe to replay)
  retry 1/3 in 20ms after UNAVAILABLE
  retry 2/3 in 40ms after UNAVAILABLE
  -> Alice after 3 requests
2. 429 with Retry-After: 1 beats our own backoff
  retry 1/3 in 1000ms after RATE_LIMITED
  -> Bob
3. a 503 on POST is not replayed
  -> 503 after 1 request
4. a slow server hits the per-attempt timeout, then recovers
  retry 1/3 in 20ms after TIMEOUT
  -> Chidi
5. malformed JSON is a parse error, not retried
  -> parse | The server replied with something that is not JSON.
6. nothing is listening on the port
  retry 1/1 in 20ms after ECONNREFUSED
  -> network ECONNREFUSED | Cannot reach the server (ECONNREFUSED).
7. the iterator hides the paging
  -> Alice, Bob, Chidi, Dara, Eli (3 requests)
8. the CLI turns every failure into a sentence
  -> fail | Nothing exists with that id.
  -> fail | That token looks wrong - please double-check it.
  -> fail | usage: user-cli <command>
sleeps requested: 20, 40, 1000, 20, 20

Backoff ကို ကိန်းဂဏန်းနဲ့ ကြည့်ခြင်း

Base delay 200 ms နဲ့ cap 5 စက္ကန့်ဆိုရင် failure တိုင်းပြီးနောက် cap က တားတဲ့အထိ ရပ်နားချိန်က နှစ်ဆတိုးပါတယ်။ Full jitter က အဲဒီ ceiling နဲ့ သုညကြား random စောင့်ချိန်ကို ရွေးလို့ တစ်ချိန်တည်းမှာ ကျရှုံးခဲ့တဲ့ client တွေကို ပြန့်သွားစေပါတယ်။

schedule.mjs
// The wait before the next try doubles each time, up to a cap
const baseDelayMs = 200;
const maxDelayMs = 5000;

for (let failed = 1; failed <= 6; failed++) {
  const ceiling = Math.min(maxDelayMs, baseDelayMs * 2 ** (failed - 1));
  console.log(`after failure ${failed}: wait ${ceiling} ms (jitter: 0-${ceiling} ms)`);
}

Retry-After မှာ အသေးစိတ် တစ်ခုထပ်ပါပါတယ်၊ စက္ကန့်အရေအတွက် ဒါမှမဟုတ် HTTP date အဖြစ် ရောက်လာပါတယ်။ Parser သေးသေးလေးက နှစ်မျိုးလုံးကို ကိုင်တွယ်၊ အတိတ်ကာလ date ကို သုညလို သဘောထား၊ ဖတ်မရတာအားလုံးအတွက် undefined ပြန်ပေးလို့ code က ကိုယ်ပိုင် backoff ကို ပြန်သုံးပါတယ်။

retry-after.mjs
// Retry-After comes in two shapes: a number of seconds, or an HTTP date
function parseRetryAfter(value, now = Date.now()) {
  if (!value) return undefined;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000;
  const when = Date.parse(value);
  return Number.isNaN(when) ? undefined : Math.max(0, when - now);
}

const now = Date.parse("Wed, 21 Oct 2026 07:27:58 GMT"); // fixed clock for the demo
console.log("seconds form:", parseRetryAfter("3", now));
console.log("date form:   ", parseRetryAfter("Wed, 21 Oct 2026 07:28:00 GMT", now));
console.log("date in past:", parseRetryAfter("Wed, 21 Oct 2026 07:20:00 GMT", now));
console.log("nonsense:    ", parseRetryAfter("soon", now));
console.log("missing:     ", parseRetryAfter(null, now));

ကျွန်တော်တို့ client က server က maxDelayMs ထက် ပိုကြာကြာ တောင်းရင် စောင့်ဖို့ ငြင်းပြီး 429 ကို throw လုပ်ပါတယ်။ တစ်နာရီ အိပ်နေမယ့် script ထက် ပီပြင်စွာ ကျရှုံးပြီး caller ကို ဆုံးဖြတ်ခွင့်ပေးတဲ့ script က ပိုကောင်းပါတယ်။

Retry လုပ်တဲ့ request ရဲ့ timeline

အောက်က diagram က demo ရဲ့ scenario 1 နဲ့ scenario 3 ကို လိုက်ပြပါတယ်။ တူညီတဲ့ 503 ကို GET က အချိန်ယူပြီး ကျော်လွှားတဲ့အခါ POST က ချက်ချင်း throw လုပ်တာကို သတိထားကြည့်ပါ။

text
Retry timeline
--------------
GET /users/u_1   (timeoutMs 300, baseDelayMs 20, retries 3, jitter off)

  attempt 1  ----> 503 UNAVAILABLE
                   wait 20 ms
  attempt 2  ----> 503 UNAVAILABLE
                   wait 40 ms
  attempt 3  ----> 200 OK   user returned to the caller

POST /users   (the same 503 on the first attempt)

  attempt 1  ----> 503 UNAVAILABLE
                   thrown at once: the server may already have saved the user

Code နဲ့ ကိုက်တဲ့ README ရေးခြင်း

ဘယ်သူမှ run မနိုင်တဲ့ client က မပြီးသေးပါဘူး။ README က နောက်ဆုံးအဆင့်ဖြစ်ပြီး မှန်ကန်နေစေဖို့ အလွယ်ဆုံးနည်းက CLI က help ကို print လုပ်တဲ့ နေရာတူတူကနေ command စာရင်းကို ကူးတာပါ။

README.md
# user-cli

A small command-line client for the Users API.

## Setup

1. Copy `.env.example` to `.env` and paste your own token.
2. Run `node --env-file=.env cli.mjs list` (Node 20.6 or newer).

## Commands

| Command | What it does |
| --- | --- |
| `list` | show the first page of users |
| `get <id>` | show one user |
| `create <name> <email>` | add a user |
| `update <id> key=value` | change the name and/or email |
| `delete <id>` | remove a user |

## When something fails

- `401`: the token is wrong or expired, check `.env`
- `429`: you are sending too fast, the client waits and retries by itself
- `timeout` or `network`: the server is slow or unreachable, try again later

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Production client တိုင်းမှာ ဒီ layer ရှိပါတယ်၊ လက်နဲ့ ရေးထားတာဖြစ်ဖြစ် SDK ထဲ ပါလာတာဖြစ်ဖြစ်ပါ။ Official library တွေက default timeout၊ transient error အတွက် retry နဲ့ typed error တွေပါလာတာ အကြောင်းရှိပါတယ်၊ consumer ဘက်က outage အများစုက 'API ပျက်နေတယ်' မဟုတ်ဘဲ 'API နှေးလို့ ကျွန်တော်တို့ အဆုံးမရှိ စောင့်ခဲ့တယ်' ဒါမှမဟုတ် 'API နည်းနည်းယိမ်းလို့ ကျွန်တော်တို့ အလွန်အကျွံ ပြန်ကြိုးစားခဲ့တယ်' ဆိုတာမျိုးပါ။

Team တွေက အဲဒီ ဖွဲ့စည်းပုံပေါ်မှာပဲ monitoring ထပ်ထည့်ပါတယ်။ Error kind နဲ့ code ကို log လုပ် (Authorization header ကိုတော့ ဘယ်တော့မှ မလုပ်ပါ)၊ endpoint တစ်ခုချင်းစီအလိုက် retry ကို ရေတွက်ပြီး retry rate တက်လာရင် alert ပေးပါတယ်။ ဒီ lesson ကျော်လွန်ရင် circuit breaker တွေ (ဆက်ကျရှုံးနေတဲ့ dependency ကို ခေါ်ခြင်းရပ်) နဲ့ bulkhead တွေ (နှေးတဲ့ API တစ်ခုက connection အားလုံးကို မစားစေ) ရှိပါတယ်။ နှစ်ခုစလုံးက ဒီမှာ ရေးခဲ့တဲ့ classification ပေါ်မှာ တည်ဆောက်ထားတာပါ။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

Method အားလုံးကို ပြန်ကြိုးစားတာ

503 ပြီးနောက် POST ကို ပြန်ပို့ရင် record ကို နှစ်ကြိမ် ဖန်တီးနိုင်ပါတယ်၊ server က မပျက်ခင် သိမ်းပြီးသားဖြစ်နိုင်လို့ပါ။ GET, HEAD, PUT, DELETE ကို အလိုအလျောက် ပြန်ကြိုးစားပါ၊ POST အတွက်တော့ 429 ကိုပဲ ပြန်ကြိုးစားပါ၊ provider က ပံ့ပိုးရင် idempotency key ပို့ပါ။

Backoff ရော jitter ပါမပါ ချက်ချင်း ပြန်ကြိုးစားတာ

ရပ်နားချိန်မပါတဲ့ loop က တစ်ကြိမ်ယိမ်းတာကို request ရေလွှမ်းမိုးမှု ဖြစ်စေပါတယ်။ အကြိမ်တိုင်း စောင့်ချိန်ကို နှစ်ဆတိုး၊ cap ထား၊ jitter ထည့်ပါ၊ ဒါမှ client ထောင်ချီက တစ်ချိန်တည်း ပြန်မလာမှာပါ။

Attempt အားလုံးမှာ AbortSignal တစ်ခုတည်းကို မျှဝေသုံးတာ

Loop အပြင်မှာ တစ်ကြိမ်ပဲ ဖန်တီးထားတဲ့ signal က ပထမ timeout ပြီးနောက် abort ဖြစ်နေတုန်းမို့ နောက်ဆက်တွဲ attempt တိုင်း ချက်ချင်း ကျရှုံးပါတယ်။

Retry-After ကို ကန့်သတ်ချက်မရှိဘဲ ယုံတာ

3600 လို့ ပြောတဲ့ header က script ကို တစ်နာရီ အိပ်စေပါလိမ့်မယ်။ အများဆုံးတန်ဖိုးနဲ့ နှိုင်းယှဉ်ပြီး ကြာလွန်းရင် 429 နဲ့ လက်လျှော့ပါ။

တတိယအမှားကို code အနည်းငယ်နဲ့ သက်သေပြလို့ရပါတယ်၊ ပထမ attempt က deadline အပြည့်စောင့်ပြီး ဒုတိယက ချက်ချင်း ကျရှုံးတာ ကြည့်ပါ။

shared-signal.mjs
import http from "node:http";

const server = http.createServer(() => {}); // accepts the request and never answers
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}/`;

// Mistake: one signal created OUTSIDE the retry loop
const signal = AbortSignal.timeout(100);
for (const attempt of [1, 2]) {
  const started = Date.now();
  try {
    await fetch(url, { signal });
  } catch (err) {
    const instant = Date.now() - started < 50;
    console.log(`attempt ${attempt}: ${err.name}, failed instantly: ${instant}`);
  }
}
server.closeAllConnections();
server.close();

Mini challenge

Reusable withBackoff helper ကို ထုတ်ယူပါ

request() ထဲက retry loop က fetch အတွက်ပဲ အလုပ်လုပ်ပါတယ်။ အဲဒါကို async function မည်သည့်အတွက်မဆို သုံးလို့ရတဲ့ generic helper withBackoff(fn, options) အဖြစ် ထုတ်ယူပါ။ fn(attempt) ကို ခေါ်၊ အောင်မြင်ရင် ရပ်၊ shouldRetry က မဖြစ်ဘူးပြောရင် ဒါမှမဟုတ် retry ကုန်ရင် ချက်ချင်း ပြန် throw လုပ်ပြီး မဟုတ်ရင် min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1)) ကို စောင့်ရပါမယ်၊ error က ကိုယ်ပိုင် retryAfterMs ပါရင်တော့ မစောင့်ပါဘူး။

  • အောင်မြင်ရင် { value, attempts, delays } ကို return ပြန်ပြီး delays မှာ စောင့်ချိန်တိုင်း ပါရမယ်
  • Permanent error (shouldRetry က false ပြန်) ကို attempt တစ်ကြိမ်အတိအကျပြီးရင် ပြန် throw လုပ်ရမယ်
  • Retry တွေကုန်ရင် နောက်ဆုံး error ကို attempts နဲ့ delays ကပ်ပြီး ပြန် throw လုပ်ရမယ်
  • retryAfterMs ပါတဲ့ error က formula အစား အဲဒီ value ကို သုံးရမယ်
  • Test က တကယ်မစောင့်အောင် sleep ကို ပြင်ပကနေ ထည့်လို့ရရမယ်
with-backoff.mjs
// Extract the retry loop into a helper that works for ANY async function.

async function withBackoff(fn, options = {}) {
  // options: retries, baseDelayMs, maxDelayMs, shouldRetry(err), sleep(ms)
  // TODO 1: call fn(attempt) inside a loop, starting at attempt 1
  // TODO 2: on success return { value, attempts, delays }
  // TODO 3: rethrow at once when shouldRetry(err) is false or the retries are used up
  // TODO 4: otherwise wait min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1)),
  //         or err.retryAfterMs when the error carries one, then loop again
}

// TODO 5: test four cases with a fake sleep (so nothing really waits):
//         flaky then ok / permanent error / always failing / retryAfterMs hint

ရလဒ်: Line ခုနစ်ကြောင်းပါ။ attempt 3 မှာ အောင်မြင်တဲ့ flaky call (delay 100 နဲ့ 200)၊ attempt 1 ကြိမ်ပြီး delay မရှိတဲ့ permanent error၊ attempt 4 ကြိမ်ပြီး delay 100, 200, 400 ပါတဲ့ ကုန်ဆုံးသွားတဲ့ call နဲ့ server ရဲ့ 1500 ms ကို စောင့်တဲ့ throttled call တို့ပါ။

အရိပ်အမြွက် ကြည့်ရန်

for (let attempt = 1; ; attempt++) ထဲမှာ try/catch ထည့်ပါ။ Delay မတွက်ခင် attempt > retries နဲ့ !shouldRetry(err) ကို အရင်စစ်ပါ၊ delay တိုင်းကို array ထဲ push လုပ်ပါ၊ ဒါမှ caller က schedule ကို မြင်ရမယ်။

အဖြေ ကြည့်ရန်
with-backoff.mjs
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Generic retry helper: works for any async function, not only fetch
async function withBackoff(fn, options = {}) {
  const { retries = 3, baseDelayMs = 100, maxDelayMs = 1000 } = options;
  const { shouldRetry = () => true, sleep = wait } = options;
  const delays = [];
  for (let attempt = 1; ; attempt++) {
    try {
      return { value: await fn(attempt), attempts: attempt, delays };
    } catch (err) {
      if (attempt > retries || !shouldRetry(err)) {
        err.attempts = attempt;
        err.delays = delays;
        throw err;
      }
      const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
      const delay = err.retryAfterMs ?? backoff; // the server's hint wins
      delays.push(delay);
      await sleep(delay);
    }
  }
}

// Test doubles: a transient error, and a sleep that does not really wait
const transient = (message, extra = {}) =>
  Object.assign(new Error(message), { transient: true, ...extra });
const isTransient = (err) => err.transient === true;
const noSleep = async () => {};
const opts = { shouldRetry: isTransient, sleep: noSleep };

// 1. fails twice, then works
const flaky = await withBackoff(async (attempt) => {
  if (attempt < 3) throw transient("503");
  return "ok";
}, opts);
console.log(`flaky: ${flaky.value} after ${flaky.attempts} attempts`);
console.log(`delays [${flaky.delays}]`);

// 2. a permanent error must not be retried
try {
  await withBackoff(async () => {
    throw new Error("bad request");
  }, opts);
} catch (err) {
  console.log(`fatal: "${err.message}" after ${err.attempts} attempt`);
  console.log(`delays [${err.delays}]`);
}

// 3. always failing: stop after the retry limit and rethrow the last error
try {
  await withBackoff(async () => {
    throw transient("still down");
  }, { ...opts, retries: 3 });
} catch (err) {
  console.log(`exhausted: "${err.message}" after ${err.attempts} attempts`);
  console.log(`delays [${err.delays}]`);
}

// 4. the delay can come from the server instead of the formula
const throttled = await withBackoff(async (attempt) => {
  if (attempt === 1) throw transient("429", { retryAfterMs: 1500 });
  return "ok";
}, opts);
console.log(`throttled: ${throttled.value}, delays [${throttled.delays}]`);

Quick Quiz 1 / 3

baseDelayMs = 200၊ maxDelayMs = 5000 ဖြစ်ပြီး jitter ပိတ်ထားရင် တတိယ attempt မအောင်မြင်ပြီးနောက် (attempt = 3) backoffDelay က ဘယ်လောက်စောင့်မလဲ။

Quick Quiz 2 / 3

Server က အောက်ပါ request တစ်ခုချင်းစီကို 503 နဲ့ ဖြေပါတယ်။ Part 3 client က ဘယ်ဟာကို အလိုအလျောက် ပြန်မကြိုးစားဘူးလဲ။

Quick Quiz 3 / 3

Client တစ်ခုက const signal = AbortSignal.timeout(2000) ကို retry loop အပြင်မှာ တစ်ကြိမ်ပဲ ဖန်တီးပြီး attempt တိုင်းကို ပေးထားပါတယ်။ ဘာမှားမလဲ။

မှတ်ထားရမယ့် အချက်များ

  • Attempt တိုင်းကို AbortSignal.timeout ကိုယ်ပိုင်ပေးပါ၊ ဒါမှ တိတ်ဆိတ်နေတဲ့ server က command ကို မရပ်စေနိုင်ဘူး
  • ဘေးကင်းတာကိုပဲ ပြန်ကြိုးစားပါ၊ 429 ကို အမြဲ၊ network error၊ timeout နဲ့ 502/503/504 ကို GET, HEAD, PUT, DELETE အတွက်သာ၊ POST ကို မျက်စိမှိတ်ပြန်မပို့ပါနဲ့
  • Jitter ပါတဲ့ exponential backoff သုံး၊ Retry-After ကို လေးစား၊ စောင့်ချိန်ကို cap ထားပြီး retry အကြိမ်ရေ သတ်မှတ်ပြီးရင် ရပ်ပါ
  • Failure ကို http, network, timeout, parse အဖြစ်ခွဲပြီး typed result ပြန်ပေးပါ၊ ဒါမှ CLI က ဖော်ရွေတဲ့ message print လုပ်နိုင်မယ်
  • Fault injection နဲ့ ပြင်ပက ထည့်လို့ရတဲ့ sleep ကြောင့် retry စည်းမျဉ်းတိုင်းကို မစောင့်ဘဲ test လုပ်နိုင်တယ်

OWASP API Security Project — OWASP

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Mini Project — Part 3: Error Handling နဲ့ Polish | Thuta Learning