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

Error Handling

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

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

  • 2xx, 4xx, 5xx class တွေကို ရှင်းပြပြီး 404 မှာ fetch က resolve ဖြစ်ပေမဲ့ response မရတဲ့အခါမှ throw လုပ်တာကို ပြောနိုင်ဖို့
  • JSON error body (code, message, field တစ်ခုချင်း message) ကို ဖတ်ပြီး 400, 422, 409 ကို ခွဲခြားနိုင်ဖို့
  • Network error, 5xx နဲ့ 429 ကိုပဲ exponential backoff, full jitter, Retry-After နဲ့ retry လုပ်နိုင်ဖို့
  • AbortSignal.timeout နဲ့ timeout ထည့်ပြီး TimeoutError ကို သိနိုင်ဖို့

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

Error handling ကို ရိုးရိုးလေး ပြောရရင်

API ခေါ်တာ မအောင်မြင်တဲ့အခါ "မအောင်မြင်ဘူး" ဆိုတာတစ်ခုတည်းနဲ့ အချက်အလက် မလုံလောက်ပါဘူး။ Server က သင့် request မှားတယ်လို့ ပြောတာ (4xx status) ဖြစ်နိုင်တယ်၊ သူ့ဘက်က ပျက်နေတာ ဒါမှမဟုတ် အလုပ်များနေတာ (5xx status) ဖြစ်နိုင်တယ်၊ ဒါမှမဟုတ် network ပြတ်သွားလို့ ဒါမှမဟုတ် ကြာလွန်းလို့ server ဆီ ရောက်တောင် မရောက်လိုက်တာလည်း ဖြစ်နိုင်ပါတယ်။ ဒီအမျိုးအစားတစ်ခုချင်းစီက တုံ့ပြန်ပုံ မတူပါဘူး: input ကို ပြင်မလား၊ ခဏစောင့်ပြီး ပြန်ကြိုးစားမလား၊ user ကို ပြောပြီး ရပ်မလား။

ဒါကြောင့် ကောင်းတဲ့ client က လုပ်ဆောင်ခင် failure တိုင်းကို အုပ်စုတစ်ခုထဲ အရင်ခွဲပါတယ်။ Status code က ဒီအလုပ်ကို လွယ်စေပါတယ်: ပထမဂဏန်းက class ပါ။ 2xx က အောင်မြင်တယ်၊ 4xx က client ဘက်က တစ်ခုခု ပြင်ရမယ်၊ 5xx က server မှာ ပြဿနာရှိတယ်၊ status လုံးဝမရှိတဲ့ အခြေအနေတွေကတော့ network failure နဲ့ timeout တွေပါ။

Problem → Why → Solution

ပြဿနာ: try/catch နဲ့ error အားလုံး ကာထားပြီလို့ ထင်မိခြင်း

အောက်က function က fetch ကို try/catch ထဲထည့်ထားပြီး error အားလုံး ကာပြီလို့ ယုံထားပါတယ်။ တကယ်တော့ 404 ဖြစ်ရင် error body ကို user တစ်ယောက်လို ပြန်ပေးလိုက်ပါတယ်။ Network ပြတ်ရင်တော့ ဘာမှ မစောင့်ဘဲ တစ်ရာကြိမ် tight loop နဲ့ ပြန်ကြိုးစားပါတယ်၊ timeout လည်း မရှိပါဘူး။ Proxy က 502 HTML page ပို့ရင် res.json() က throw လုပ်ပြီး အဲဒါလည်း retry loop ထဲ ရောက်ပါတယ်။ ဆိုလိုတာက တကယ့် HTTP error တွေကို လျစ်လျူရှုထားတဲ့ code ကပဲ မျက်စိမှိတ်ပြီး retry လုပ်ကာ server ကို ဝိုင်းထိုးနေတာပါ။

blind-retry.js
async function getUser(id) {
  for (let i = 0; i < 100; i++) {
    try {
      const res = await fetch("/v1/users/" + id);
      const user = await res.json(); // 404 and 500 bodies come back as "users"
      return user;
    } catch (err) {
      // network error or invalid JSON: retry immediately, whatever the cause
    }
  }
}

Failure တစ်ခုစီမှာ အကြောင်းရှိပြီး အကြောင်းက တုံ့ပြန်ပုံကို ဆုံးဖြတ်တယ်

Retry က ယာယီပြဿနာတွေကိုပဲ ပြင်နိုင်ပါတယ်: ပြတ်သွားတဲ့ connection၊ အလုပ်များနေတဲ့ server (503)၊ rate limit window (429)။ မှားနေတဲ့ request ကိုတော့ မပြင်နိုင်ပါဘူး။ ၁၀၀ ကြိမ်မြောက်မှာလည်း 404 က 404 ပဲ၊ 422 က 422 ပဲ ဖြစ်ပြီး retry က load ပိုတက်စေတာပဲ ရှိပါတယ်။ ဒါကြောင့် စောင့်မလား၊ ပြင်မလား၊ လက်လျှော့မလားဆိုတာ မဆုံးဖြတ်ခင် အကြောင်း (status code ဒါမှမဟုတ် response မရတာ) ကို အရင်ကြည့်ရပါမယ်။

Core concept: ရလဒ်လေးမျိုး၊ တုံ့ပြန်ပုံလေးမျိုး

fetch call တစ်ခုက ရလဒ်လေးမျိုးထဲက တစ်မျိုးနဲ့ ပြီးပါတယ်။ (၁) 2xx response: body ကို သုံးပါ။ (၂) 4xx response: server က သင့်ကို နားလည်ပြီး request မှားတယ် ဒါမှမဟုတ် ခွင့်မပြုဘူးလို့ ပြောတာမို့ request ကို ပြောင်းပါ။ (၃) 5xx response: server မှာ ပျက်တာမို့ တူညီတဲ့ request ကို နောက်မှ ပြန်လုပ်ရင် အလုပ်ဖြစ်နိုင်ပါတယ်။ (၄) Response မရတာ: network failure, DNS, connection ငြင်းတာတွေအတွက် fetch က TypeError နဲ့ reject ဖြစ်ပြီး ကိုယ်ချိန်ထားတဲ့ time limit ပြည့်ရင် TimeoutError ဒါမှမဟုတ် AbortError နဲ့ reject ဖြစ်ပါတယ်။ အဓိကအချက်က fetch က (၄) မှာပဲ reject ဖြစ်တာပါ။ (၂) နဲ့ (၃) က res.ok false ပါတဲ့ fulfilled promise တွေမို့ res.ok ကို ကိုယ်တိုင် စစ်ရပါမယ်။

ကောင်းတဲ့ API က တသမတ်တည်း ပုံစံရှိတဲ့ machine-readable error body ကို ပို့ပါတယ်၊ ဥပမာ { "error": { "code": "validation_failed", "message": "...", "fields": { "email": "..." } } }။ လူဖတ်တဲ့ message အပေါ်မှာ မဟုတ်ဘဲ တည်ငြိမ်တဲ့ code အပေါ်မှာ branch လုပ်ပါ၊ field message တွေကို input ဘေးမှာ ပြပါ၊ request id ပါရင် support အတွက် log မှတ်ပါ။ Body ကို သတိထားပြီး ဖတ်ပါ: proxy နဲ့ gateway တွေက 502, 504 မှာ HTML page ပို့လေ့ရှိလို့ res.json() ကို catch ထဲမှာ ခေါ်ပြီး status ကို fallback လုပ်ပါ။

Statusဘာကို ပြောတာလဲRetry လုပ်မလား
400 / 422Request body ကို ပြင်ပါမလုပ်ပါ
401 / 403Credential ဒါမှမဟုတ် permission ပြင်ပါမလုပ်ပါ
404 / 409Target မှား ဒါမှမဟုတ် state ချင်းတိုက်နေမလုပ်ပါ
429Request များလွန်းတယ်လုပ်ပါ၊ Retry-After ပြီးမှ
502 / 503 / 504Gateway ပျက် ဒါမှမဟုတ် overloadလုပ်ပါ၊ backoff နဲ့
Response မရNetwork error ဒါမှမဟုတ် timeoutIdempotent ဆိုရင် လုပ်ပါ

400 က request ကို လုံးဝ နားမလည်နိုင်တာ (JSON ပျက်၊ Content-Type မှား) ကို ဆိုလိုပါတယ်။ 422 ကတော့ ပုံစံမှန်ပေမဲ့ တန်ဖိုးတွေ လက်မခံနိုင်တာ (email မမှန်) ကို ဆိုလိုပြီး field အလိုက် message ပါလေ့ရှိပါတယ်။ 409 က လက်ရှိ state နဲ့ တိုက်နေတာ (email ထပ်နေ) ပါ။ API တချို့က အားလုံးကို 400 နဲ့ပဲ ပြန်ကြပါတယ်၊ docs ကို စစ်ပါ။ Retry ကို ကိုယ်ဘာသာ ပျောက်သွားတဲ့ ပြဿနာတွေအတွက်ပဲ သုံးပါ: network error, timeout, 429, 502/503/504။ ကြားထဲမှာ exponential backoff (ms ၁၀၀၊ ၂၀၀၊ ၄၀၀...) နဲ့ jitter (ကျပန်းပမာဏ) ထည့်ပါ၊ ဒါမှ တစ်ပြိုင်နက် ကျသွားတဲ့ client ထောင်ချီက တစ်စက္ကန့်တည်းမှာ ပြန်မလာမှာပါ။ Server က Retry-After (စက္ကန့် ဒါမှမဟုတ် HTTP date) ပို့ရင် ခန့်မှန်းမနေဘဲ လိုက်နာပါ။ ကြိုးစားမှုအရေအတွက်ကိုလည်း ကန့်သတ်ပါ။

ကုသမှုမတိုင်ခင် ခွဲခြားစစ်ဆေးခြင်း
  1. Response မရဘူးလား? network/timeout
  2. 4xx လား? request ပြင်၊ retry မလုပ်
  3. 5xx ဒါမှမဟုတ် 429? backoff နဲ့ retry
  4. 2xx လား? body ကို parse လုပ်ပြီး သုံး

fetch က ပထမအမျိုးအစားမှာပဲ throw လုပ်ပါတယ်။ ကျန်သုံးမျိုးက ပုံမှန် response အဖြစ်ရောက်လာလို့ res.ok နဲ့ res.status ကို ခွဲခြားစစ်ဆေးတဲ့ ကိရိယာအဖြစ် သုံးရပါမယ်။

အထွေထွေ ပုံစံ

javascript
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  try {
    const res = await fetch(url, { signal: AbortSignal.timeout(ms) });
    if (res.ok) return await res.json();
    if (!isRetryable(res.status)) throw await toApiError(res);
  } catch (err) {
    if (!isRetryable(err) || attempt === maxAttempts) throw err;
  }
  await sleep(retryAfterMs ?? randomUpTo(baseMs * 2 ** attempt));
}

Loop တစ်ကြိမ်စီမှာ time limit နဲ့ request ပို့ပါတယ်၊ အောင်မြင်ရင် ပြန်ပါတယ်၊ retry လို့မရတဲ့ error ဆိုရင် ချက်ချင်း throw လုပ်ပါတယ်၊ ဒါမှမဟုတ်ရင် Retry-After သို့ jitter ပါတဲ့ backoff အတိုင်း စောင့်ပြီး ထပ်ကြိုးစားပါတယ်။

Worked example: failure အမျိုးမျိုးအတွက် request() တစ်ခုတည်း

ဒီ sample က ကိုယ့်စက်ထဲ API အသေးလေးတစ်ခု စတင်ပါတယ်၊ တကယ့် API တစ်ခု ပျက်နိုင်တဲ့ နည်းအားလုံးနဲ့ပါ: 404၊ field message ပါတဲ့ 422၊ HTML body ပါတဲ့ 502၊ နှစ်ကြိမ် 503 ပေးပြီးမှ အလုပ်ဖြစ်တဲ့ endpoint၊ Retry-After ပါတဲ့ 429 နဲ့ ဘယ်တော့မှ မဖြေတဲ့ endpoint။ request() က failure တိုင်းကို kind (network, timeout, http) tag ပါတဲ့ Error အဖြစ် ပြောင်းပေးပြီး withRetry() က ကိုယ်ဘာသာ ပျောက်နိုင်တဲ့ kind တွေကိုပဲ retry လုပ်ပါတယ်။ Retry-After ကို 0 စက္ကန့်၊ backoff ကို milliseconds ဆယ်ဂဏန်းထားထားလို့ run တစ်ခုလုံး တစ်စက္ကန့်အောက်ပဲ ကြာပါတယ်။

errors.mjs
import http from "node:http";

// A stand-in API that fails in every way a real one can.
let flakyCalls = 0;
let limitedCalls = 0;
const send = (res, status, body, headers = {}) => {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(body));
};
const fail = (res, status, code, message, { fields, headers } = {}) =>
  send(res, status, { error: { code, message, ...(fields && { fields }) } }, headers);

const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, "http://localhost");
  if (pathname === "/v1/users/u_1") {
    send(res, 200, { id: "u_1", name: "Alice" });
  } else if (pathname === "/v1/users/u_99") {
    fail(res, 404, "user_not_found", "No user with id u_99");
  } else if (pathname === "/v1/signup") {
    const fields = { email: "must be a valid email address" };
    fail(res, 422, "validation_failed", "Invalid input", { fields });
  } else if (pathname === "/v1/flaky") {
    if (++flakyCalls < 3) fail(res, 503, "unavailable", "Try again shortly");
    else send(res, 200, { ok: true });
  } else if (pathname === "/v1/limited") {
    // Retry-After: 0 keeps the lesson fast; real servers send seconds or a date
    const headers = { "Retry-After": "0" };
    if (++limitedCalls < 2) fail(res, 429, "rate_limited", "Slow down", { headers });
    else send(res, 200, { ok: true });
  } else if (pathname === "/v1/proxy") {
    res.writeHead(502, { "Content-Type": "text/html" });
    res.end("<h1>Bad Gateway</h1>");
  }
  // any other path (/v1/slow) never answers
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;

// One request() that turns every failure into an Error tagged with a kind.
async function request(url, timeoutMs = 300) {
  let res;
  try {
    res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
  } catch (cause) {
    // fetch THROWS only when no HTTP response arrived at all
    const kind = cause.name === "TimeoutError" ? "timeout" : "network";
    throw Object.assign(new Error(kind + " failure"), { kind, cause });
  }
  if (res.ok) return res.json();
  const body = await res.json().catch(() => ({})); // an error page may not be JSON
  const { code, message, fields } = body.error ?? {};
  const retryAfter = res.headers.get("retry-after");
  throw Object.assign(new Error(message ?? "HTTP " + res.status), {
    kind: "http",
    status: res.status,
    code,
    fields,
    retryAfterMs: retryAfter === null ? undefined : Number(retryAfter) * 1000,
  });
}

const RETRYABLE = new Set([429, 502, 503, 504]);
const isRetryable = (e) =>
  e.kind === "network" ||
  e.kind === "timeout" ||
  (e.kind === "http" && RETRYABLE.has(e.status));

async function withRetry(fn, maxAttempts = 4, baseMs = 20) {
  for (let attempt = 1; ; attempt++) {
    try {
      return { value: await fn(), attempts: attempt };
    } catch (err) {
      if (!isRetryable(err) || attempt === maxAttempts) throw err;
      // honour Retry-After, otherwise exponential backoff with full jitter
      const wait = err.retryAfterMs ?? Math.random() * baseMs * 2 ** attempt;
      await new Promise((resolve) => setTimeout(resolve, wait));
    }
  }
}

async function show(label, promise) {
  try {
    console.log(label + ":", JSON.stringify(await promise));
  } catch (e) {
    const parts = [e.kind];
    if (e.kind === "http") parts.push(e.status, e.code ?? "(no JSON error body)");
    if (e.kind === "network") parts.push(e.cause.cause?.code);
    if (e.fields) parts.push(JSON.stringify(e.fields));
    console.log(label + ":", parts.join(" "));
  }
}

await show("ok", request(base + "/v1/users/u_1"));
await show("missing", request(base + "/v1/users/u_99"));
await show("invalid", request(base + "/v1/signup"));
await show("proxy", request(base + "/v1/proxy"));
await show("flaky", withRetry(() => request(base + "/v1/flaky")));
await show("limited", withRetry(() => request(base + "/v1/limited")));
await show("slow", request(base + "/v1/slow", 100));

// Nothing listens on this port any more, so fetch cannot connect at all.
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const closedUrl = "http://127.0.0.1:" + closed.address().port;
await new Promise((resolve) => closed.close(resolve));
await show("offline", request(closedUrl + "/v1/users/u_1"));

server.close();
server.closeAllConnections();

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

  1. fetch throws only without a responseconst kind = cause.name === "TimeoutError" ? "timeout" : "network";

    catch ထဲရောက်လာတာက response မရတဲ့ အမှားတွေပဲ ဖြစ်ပါတယ်။ AbortSignal.timeout ပြည့်ရင် name က TimeoutError၊ ကျန်တာ (connection ငြင်း၊ DNS) က network လို့ အမျိုးအစားခွဲလိုက်ပါတယ်။

  2. Check res.ok yourselfif (res.ok) return res.json();

    404 နဲ့ 422 အတွက် fetch ရဲ့ promise က fulfilled ဖြစ်တာမို့ ဒီစာကြောင်းက success လမ်းကြောင်းကို သီးခြားထားပေးပါတယ်။ ကျန်တာအားလုံးက error body ဖတ်တဲ့ အောက်ဘက်ကို ဆက်သွားပါတယ်။

  3. Error body may not be JSONconst body = await res.json().catch(() => ({})); // an error page may not be JSON

    502 ရဲ့ <h1>Bad Gateway</h1> body ကို JSON လို့ parse လုပ်ရင် throw ဖြစ်မှာမို့ .catch နဲ့ အလွတ် object ပြောင်းပါတယ်။ ဒါကြောင့် proxy output မှာ code မပါလည်း status နဲ့ error ဆက်ထုတ်နိုင်ပါတယ်။

  4. Read Retry-AfterretryAfterMs: retryAfter === null ? undefined : Number(retryAfter) * 1000,

    Retry-After header က စက္ကန့်အရေအတွက် ဖြစ်နိုင်ပါတယ်၊ ဒီမှာ milliseconds ပြောင်းထားပါတယ်။ HTTP date အဖြစ် ပို့တဲ့ server တွေလည်း ရှိပါတယ်၊ ဒါကို challenge မှာ ကိုင်တွယ်ပါမယ်။

  5. What is retryableconst RETRYABLE = new Set([429, 502, 503, 504]);

    Status စာရင်းကို ကိုယ်တိုင် ရှင်းရှင်းလင်းလင်း ထားပါတယ်။ 404, 422 က ဒီထဲမှာ မပါလို့ ဘယ်တော့မှ retry မလုပ်ပါဘူး။

  6. Backoff with full jitterconst wait = err.retryAfterMs ?? Math.random() * baseMs * 2 ** attempt;

    Server က Retry-After ပေးထားရင် အဲဒါကို သုံးပါတယ်၊ မပေးရင် ၂ ရဲ့ power နဲ့ တိုးတဲ့ ကန့်သတ်ချက်အောက်က ကျပန်းတန်ဖိုးကို စောင့်ပါတယ်။ ?? က 0 ကို မဖယ်ပါဘူး၊ ဒါကြောင့် Retry-After: 0 ကို အတိုင်းလိုက်နာပါတယ်။

You should see
ok: {"id":"u_1","name":"Alice"}
missing: http 404 user_not_found
invalid: http 422 validation_failed {"email":"must be a valid email address"}
proxy: http 502 (no JSON error body)
flaky: {"value":{"ok":true},"attempts":3}
limited: {"value":{"ok":true},"attempts":2}
slow: timeout
offline: network ECONNREFUSED
Request တစ်ခု ပျက်သွားတဲ့အခါ ဆုံးဖြတ်ပုံ
  1. Request ပို့ပြီး time limit ထည့်ပါ
  2. Response ရလာလား၊ throw ဖြစ်လားကြည့်ပါ
  3. res.ok ကို စစ်ပြီး status class ကို ခွဲပါ
  4. Retry လို့ရရင် စောင့်ပြီး ထပ်လုပ်ပါ

2xx ရတယ်

Parse the body and return it

4xx ဒါမှမဟုတ် ကြိုးစားမှုပြည့်

Throw a typed error so the caller can show a message

422 response ကို wire ပေါ်မှာ ကြည့်ခြင်း

Error body ရဲ့ ပုံစံက API တစ်ခုလုံးမှာ တူရပါမယ်၊ ဒါမှ client က error handler တစ်ခုတည်းနဲ့ ကိုင်နိုင်မှာပါ။ အောက်က exchange မှာ client က email မမှန်တဲ့ user ကို ဖန်တီးခိုင်းလို့ server က 422 ပြန်ပါတယ်။ Status line က class ကို ပြောတယ်၊ code က ပရိုဂရမ်အတွက်၊ message က လူအတွက်၊ fields က form ထဲက input တစ်ခုချင်းအတွက်ပါ။

text
POST /v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json

{ "name": "Bob", "email": "bob-at-example" }

HTTP/1.1 422 Unprocessable Content
Content-Type: application/json

{ "error": { "code": "validation_failed",
             "message": "One or more fields are invalid",
             "fields": { "email": "must be a valid email address" } } }

ဘယ် request တွေကို retry လုပ်လို့ ရမလဲ

Timeout ဖြစ်တဲ့အခါ သင်မသိတာက server က request ကို လုပ်ပြီးသွားပြီလား မလုပ်ရသေးဘူးလားဆိုတာပါ။ Request ကို ထပ်ပို့လည်း ရလဒ် မပြောင်းတဲ့ method တွေ (idempotent) ကိုပဲ အလွတ်သဘော retry လုပ်ပါ။ POST ကတော့ record နှစ်ခု ဖန်တီးမိနိုင်ပါတယ်၊ ဒါကြောင့် Stripe လို API တွေက Idempotency-Key header ကို လက်ခံပြီး key တူရင် ပထမ response ကိုပဲ ပြန်ပေးပါတယ်။ Server က ဒီ header ကို support လုပ်တယ်လို့ docs မှာ ရေးထားမှသာ ကိုယ့် POST ကို retry လုပ်ပါ။

MethodIdempotent လားFailure ပြီး retry လုပ်မလား
GETဟုတ်ပါတယ်လုပ်လို့ရတယ်
PUT / DELETEဟုတ်ပါတယ် (ရလဒ်တူတယ်)လုပ်လို့ရတယ်
PATCHAPI ပေါ်မူတည်တယ်docs ကို စစ်ပါ
POSTမဟုတ်ပါIdempotency-Key ပါမှ
text
POST /v1/payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 7f3a9c1e-order-1042

{ "amount": 1200, "currency": "usd" }

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

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

Production client တွေက ဒီ logic ကို component တိုင်းမှာ မရေးပါဘူး။ HTTP client wrapper တစ်ခု (သို့မဟုတ် SDK) ထဲမှာ တစ်ခါတည်း ထည့်ထားပြီး UI က typed error တွေကိုပဲ လက်ခံပါတယ်။ AWS SDK တွေက throttling နဲ့ 5xx ကို backoff နဲ့ jitter ပါတဲ့ retry ကို default အနေနဲ့ လုပ်ပေးပါတယ်။ Rate limit အတွက် 429 အပြင် 403 သုံးတဲ့ provider တွေလည်း ရှိလို့ status တစ်ခုတည်းမကဘဲ Retry-After နဲ့ rate-limit header တွေကို docs အတိုင်း ဖတ်ပါ။

  • 422 ကို form ထဲက field ဘေးမှာ ပြပါတယ်၊ 401 က login ကို ပြန်ပို့ပါတယ်၊ 404 က "မတွေ့ပါ" page ပြပါတယ်၊ retry လို့ရတဲ့ error တွေက "ပြန်ကြိုးစားမယ်" ခလုတ်ကို ပြပါတယ်။
  • Log မှာ request id, status, code ပါပါတယ်၊ token, password နဲ့ ကိုယ်ရေးကိုယ်တာ data မပါစေရပါဘူး။ User ကို ပြတဲ့ message နဲ့ operator log ကို ခွဲထားပါတယ်။
  • Monitoring က 5xx ရာခိုင်နှုန်းနဲ့ retry အရေအတွက်ကို ကြည့်ပါတယ်၊ retry မြင့်လာတာက အထက်ကွင်းဆက်ပြဿနာရဲ့ အစောပိုင်းလက္ခဏာ ဖြစ်တတ်ပါတယ်။

အမှားများ

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

try/catch ကို error handling အစုံလို့ ထင်ခြင်း

fetch က 404, 422, 500 မှာ throw မလုပ်ပါဘူး၊ ဒါကြောင့် try/catch တစ်ခုတည်းနဲ့ HTTP error တွေ ပျောက်သွားပါတယ်။ res.ok ကို စစ်ပြီး error body ကို ဖတ်ပါ။

အားလုံးကို ချက်ချင်းနဲ့ အဆုံးမရှိ retry လုပ်ခြင်း

422 ကို retry လုပ်ရင် အောင်မြင်မှာ မဟုတ်ပါဘူး၊ ပြီးတော့ delay မပါရင် server ပြန်ကောင်းလာချိန်မှာတောင် သင့် client တွေက တစ်ပြိုင်နက် ဝင်ပြီး ပြန်လဲစေပါတယ်။ Retry လို့ရတဲ့ status အနည်းငယ်ကိုပဲ ရွေးပြီး backoff, jitter, ကြိုးစားမှုအများဆုံးအရေအတွက် ထည့်ပါ။

POST ကို မကာကွယ်ဘဲ retry လုပ်ခြင်း

POST ပို့ပြီး timeout ဖြစ်တုန်း server က record ဖန်တီးပြီးသား ဖြစ်နိုင်ပါတယ်။ ထပ်ပို့ရင် ငွေနှစ်ခါထုတ်တာ၊ user နှစ်ယောက်ဖြစ်တာတွေ ဖြစ်ပါတယ်။ Idempotency-Key မပါရင် မ retry ပါနဲ့။

Timeout မထည့်ခြင်း

fetch မှာ default timeout မရှိပါဘူး၊ server က connection ကို ဖွင့်ထားပြီး မဖြေရင် promise က အကန့်အသတ်မရှိ စောင့်နေပါလိမ့်မယ်။ Request တိုင်းမှာ signal: AbortSignal.timeout(ms) ထည့်ပါ။

Best Practices

Best practices

  • Request function တစ်ခုထဲမှာ timeout, res.ok စစ်တာ, error body ဖတ်တာ, error အမျိုးအစား tag ထည့်တာကို စုထားပါ။
  • Error ပုံစံကို code, message, fields နဲ့ request id အဖြစ် တသမတ်တည်း ထားပါ၊ code ပေါ်မှာ branch လုပ်ပါ။
  • Retry policy ကို test လုပ်ပါ: random နဲ့ sleep ကို parameter အဖြစ် ထုတ်ထားရင် delay ကို ခန့်မှန်းနိုင်တဲ့ test တွေ ရေးလို့ရပါတယ်။

Mini challenge

Retry policy ကို ကိုယ်တိုင် ရေးကြည့်ပါ

Function နှစ်ခု ရေးပါ။ shouldRetry(method, status, hasIdempotencyKey) က retry လုပ်သင့်မလား ဆုံးဖြတ်ပါတယ် (status က null ဆိုရင် response မရတာ)။ retryDelayMs(attempt, retryAfter, now, random) က စောင့်ရမယ့် milliseconds ကို ပြန်ပေးပါတယ်။ Retry-After က စက္ကန့်ဂဏန်း ဒါမှမဟုတ် HTTP date နှစ်မျိုးလုံး ဖြစ်နိုင်ပါတယ်။

  • 429 မဟုတ်တဲ့ 4xx ကို ဘယ်တော့မှ retry မလုပ်ပါနဲ့
  • null, 429, 502, 503, 504 ကို idempotent method ဒါမှမဟုတ် Idempotency-Key ရှိမှသာ retry လုပ်ပါ
  • Retry-After "3" က 3000 ms၊ HTTP date က ရက်စွဲ အနုတ် now (0 အောက် မဆင်းရ)
  • Header မရှိရင် random() * min(5000, 100 * 2 ** attempt) ကို သုံးပါ
retry-policy.js
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);

// status is null when no response arrived (network error or timeout)
function shouldRetry(method, status, hasIdempotencyKey = false) {
  // TODO: a 4xx other than 429 can never be fixed by retrying
  // TODO: retry null, 429, 502, 503 and 504 only when the call is safe to repeat
}

// retryAfter is the raw Retry-After header value, or null
function retryDelayMs(attempt, retryAfter, now, random = Math.random) {
  // TODO: "3" means 3000 ms
  // TODO: an HTTP date means "that date minus now", never below 0
  // TODO: otherwise use full jitter, capped at 5000 ms
}

ရလဒ်: Output ၁၀ ကြောင်း: true, false, true, false, true, 3000, 5000, 0, 400, 5000။

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

HTTP date ကို Date.parse နဲ့ milliseconds ပြောင်းပြီး now ကို နုတ်ပါ၊ ဂဏန်းသက်သက်ဖြစ်မဖြစ်ကို regular expression ဒါမှမဟုတ် Number.isInteger နဲ့ အရင်စစ်ပါ။ Test အတွက် random ကို parameter ထားထားလို့ () => 0.5 လို့ ပေးပြီး 400 ကို ထွက်စေနိုင်ပါတယ်။

အဖြေ ကြည့်ရန်
retry-policy-solution.js
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);

function shouldRetry(method, status, hasIdempotencyKey = false) {
  if (status !== null && status >= 400 && status < 500 && status !== 429) return false;
  const transient = status === null || [429, 502, 503, 504].includes(status);
  return transient && (IDEMPOTENT.has(method) || hasIdempotencyKey);
}

function retryDelayMs(attempt, retryAfter, now, random = Math.random) {
  if (retryAfter !== null) {
    if (/^[0-9]+$/.test(retryAfter)) return Number(retryAfter) * 1000;
    const date = Date.parse(retryAfter);
    if (!Number.isNaN(date)) return Math.max(0, date - now);
  }
  return Math.round(random() * Math.min(5000, 100 * 2 ** attempt));
}

console.log(shouldRetry("GET", 503));
console.log(shouldRetry("POST", 503));
console.log(shouldRetry("POST", 503, true));
console.log(shouldRetry("GET", 422));
console.log(shouldRetry("DELETE", null));
console.log(retryDelayMs(1, "3", 0));
const now = Date.parse("Wed, 21 Oct 2015 07:28:00 GMT");
console.log(retryDelayMs(1, "Wed, 21 Oct 2015 07:28:05 GMT", now));
console.log(retryDelayMs(1, "Wed, 21 Oct 2015 07:27:00 GMT", now));
console.log(retryDelayMs(3, null, now, () => 0.5));
console.log(retryDelayMs(10, null, now, () => 1));

Quick Quiz 1 / 3

fetch(url) က status 404 ပါတဲ့ Response နဲ့ resolve ဖြစ်ပါတယ်။ ဘယ်ဟာမှန်လဲ။

Quick Quiz 2 / 3

GET request တစ်ခုအတွက် အလိုအလျောက် retry လုပ်ဖို့ ဘယ် failure က ဘေးကင်းပြီး ကျိုးကြောင်းဆီလျော်လဲ။

Quick Quiz 3 / 3

POST /v1/payments က timeout ဖြစ်သွားတယ်။ ပြန်ပို့ဖို့ အဘေးကင်းဆုံး နည်းက ဘာလဲ။

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

  • fetch က response မရတဲ့အခါမှ reject ဖြစ်ပါတယ်၊ 4xx နဲ့ 5xx က res.ok false ပါတဲ့ ပုံမှန် response တွေပါ။
  • Error body ကို တသမတ်တည်း ပုံစံနဲ့ ဖတ်ပါ: code ပေါ်မှာ branch လုပ်၊ 400 (နားမလည်), 422 (တန်ဖိုးမှား), 409 (state တိုက်) ကို ခွဲပါ။
  • Network error, timeout, 429, 502/503/504 ကိုပဲ exponential backoff + jitter + Retry-After နဲ့ retry လုပ်ပါ၊ ကြိုးစားမှု ကန့်သတ်ပါ။
  • Idempotent မဟုတ်တဲ့ POST ကို Idempotency-Key မပါဘဲ မ retry ပါနဲ့၊ request တိုင်းမှာ AbortSignal.timeout ထည့်ပါ။

RFC 9110 — HTTP Semantics — IETF

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

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

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