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

Response Shape & Status Codes

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

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

  • Status code အမျိုးအစား (2xx, 4xx, 5xx) နဲ့ အသုံးများတဲ့ code တွေက ဘာကို ပြောလဲ ရှင်းပြနိုင်ဖို့
  • res.json() မခေါ်ခင် Content-Type နဲ့ 204 ကို စစ်ပြီး ဘာကြောင့် SyntaxError တက်လဲ ရှင်းပြနိုင်ဖို့
  • Envelope နဲ့ bare resource ကို နှိုင်းယှဉ်ပြီး API တစ်ခုလုံးမှာ တစ်ပုံစံတည်း ရွေးချယ်နိုင်ဖို့
  • Error response ကို code နဲ့ message ပါတဲ့ ပုံစံတစ်ခုတည်းနဲ့ ပြန်ပြီး ထိခိုက်လွယ်တဲ့ အသေးစိတ်ကို မဖော်ပြဘဲ ထားနိုင်ဖို့

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

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

Response ဆိုတာ server က request တစ်ခုကို ပြန်ဖြေတဲ့ အဖြေပါ၊ အပိုင်းသုံးပိုင်း ပါပါတယ်။ Status code က 'အဆင်ပြေသလား၊ ဘာမှားလဲ' ကို ဂဏန်းတစ်ခုနဲ့ ပြောပါတယ်။ Header တွေက အထဲက အချက်အလက်ကို ဖော်ပြတဲ့ label တွေပါ (ဥပမာ Content-Type)။ Body ကတော့ တကယ့် data ပါ။ စားသောက်ဆိုင်မှာ စားပွဲထိုးရဲ့ ခေါင်းညိတ်ပုံ၊ ဗူးပေါ်က label နဲ့ ဗူးထဲက အစားအစာလို သဘောထားနိုင်ပါတယ်။

Client code ကောင်းကောင်းရေးဖို့ အဲဒီ အပိုင်းတွေကို အစီအစဉ်တကျ ဖတ်ရပါမယ်: status ကို အရင်၊ ပြီးရင် Content-Type၊ ပြီးမှ body ပါ။ ဒီအစီအစဉ်ကို မလိုက်ဘဲ တိုက်ရိုက် res.json() ခေါ်တဲ့ code တွေက အဆင်ပြေတဲ့ ရက်မှာပဲ အလုပ်လုပ်ပြီး ဖောက်ပြန်တဲ့ response တစ်ခု ရောက်လာရင် ပျက်သွားပါတယ်။

Problem → Why → Solution

ပြဿနာ: response အားလုံးကို JSON လို့ ယူဆမိတာ

Developer တစ်ယောက်က user တစ်ယောက်ကို ဖတ်တဲ့ code ရေးပါတယ်: res.json() ခေါ်ပြီး data field ကို ထုတ်ယူပါတယ်။ Happy path မှာ အလုပ်လုပ်ပါတယ်။ ဒါပေမဲ့ user မရှိရင် body က { error: ... } ဖြစ်လို့ data က undefined ဖြစ်ပြီး TypeError တက်ပါတယ်။ DELETE ကို 204 နဲ့ ဖြေရင် body အလွတ်ကို JSON လို့ parse လုပ်ရင်း SyntaxError တက်ပါတယ်။ Gateway က HTML page ပြန်ရင်လည်း SyntaxError ပါပဲ။

assumes-json.js
// BROKEN: assumes every response is JSON with a "data" field
const res = await fetch("https://api.example.com/v1/users/u_9");
const { data } = await res.json();
console.log(data.name.toUpperCase());

// 404 -> body is { "error": ... }, so data is undefined: TypeError
// 204 -> res.json() throws on the empty body: SyntaxError
// 502 -> a gateway sends HTML: SyntaxError at the "<"

Response တစ်ခုက ပုံစံ အများကြီး ဖြစ်နိုင်တယ်

Endpoint တစ်ခုချင်းစီက အောင်မြင်ရင် data၊ မအောင်မြင်ရင် error၊ အချို့ အခြေအနေမှာ body လုံးဝမပါ၊ proxy ကြားထဲမှာ ပျက်ရင် HTML စတဲ့ ပုံစံအမျိုးမျိုး ပြန်နိုင်ပါတယ်။ Status code နဲ့ Content-Type ကသာ ဘယ်ပုံစံကို ရောက်လာတယ်ဆိုတာ ပြောပြပါတယ်။ ဒါကြောင့် body ကို မဖတ်ခင် အဲဒီနှစ်ခုကို အရင်ကြည့်ပြီး ပုံစံတစ်ခုချင်းစီကို သီးသန့် ကိုင်တွယ်ရပါမယ်။

Core concept: status, Content-Type, ပြီးမှ body

Response ရဲ့ ပထမ line က status line ပါ (HTTP/1.1 200 OK)၊ နောက်မှာ header တစ်ကြောင်းစီ၊ လွတ်တဲ့ line တစ်ကြောင်း၊ ပြီးမှ body ပါ။ Status code ရဲ့ ပထမဂဏန်းက အမျိုးအစားကို ပြောပါတယ်: 2xx က အောင်မြင်၊ 3xx က redirect ဒါမှမဟုတ် cache ကို သုံးပါ (304)၊ 4xx က client ရဲ့ အမှား၊ 5xx က server ရဲ့ အမှား။ Client က 4xx ကို ကိုယ့် request ပြင်ပြီးမှ ပြန်ပို့ရမယ်၊ 5xx ကိုတော့ နောက်မှ ပြန်ကြိုးစားနိုင်တယ်လို့ ယူဆပါတယ်။

Statusအဓိပ္ပာယ်
200 OKအောင်မြင်ပြီး body ပါ
201 Createdအသစ်ဖန်တီးပြီး၊ Location header က URL ကို ပြော
204 No Contentအောင်မြင်ပေမဲ့ body လုံးဝ မပါ
400 / 422Request ပုံစံမှား / validation ကျ
401 / 403 / 404Authenticate မလုပ်နိုင် / ခွင့်မရှိ / မတွေ့
429Request များလွန်း၊ Retry-After ကို ကြည့်
500 / 502 / 503Server အမှား / gateway အမှား / ခဏမရနိုင်

Content-Type က body ကို ဘယ်လို ဖတ်ရမလဲ ပြောပါတယ် (application/json; charset=utf-8)။ res.json() ခေါ်မယ်ဆိုရင် အဲဒါ JSON လို့ ပြောထားမှ ခေါ်ပါ၊ မဟုတ်ရင် gateway ရဲ့ HTML error page ကို parse လုပ်ရင်း Unexpected token '<' ဆိုတဲ့ SyntaxError တက်ပါတယ်။ 204 က body လုံးဝ မပါတာမို့ res.json() က Unexpected end of JSON input နဲ့ ပျက်ပါတယ်၊ ဒါကြောင့် 204 ကို အရင်စစ်ပါ။

Body ရဲ့ ပုံစံနှစ်မျိုး ရှိပါတယ်: bare resource ({ "id": "u_1", ... }) နဲ့ envelope ({ "data": ..., "meta": ... })။ Envelope က list မှာ pagination လို အချက်တွေ ထည့်ဖို့ နေရာပေးပြီး bare ကတော့ ရိုးရှင်းပါတယ်။ ဘယ်ဟာကိုပဲ ရွေးရွေး API တစ်ခုလုံးမှာ တစ်ပုံစံတည်း ထားပါ။ Error ကိုလည်း endpoint တိုင်းမှာ { "error": { "code": ..., "message": ... } } လို တူညီတဲ့ ပုံစံနဲ့ ပြန်ပါ၊ code က program အတွက်၊ message က လူအတွက်ပါ။ "success": true လို flag ကတော့ status code နဲ့ ထပ်နေပြီး နှစ်ခု မကိုက်ညီနိုင်ပါတယ်။

Response ကို အပြင်ကနေ အထဲကို ဖတ်ခြင်း
  1. Status: အောင်မြင်လား မအောင်မြင်ဘူးလား
  2. Content-Type: JSON လား တခြားလား
  3. Body အလွတ်လား (204)
  4. Parse: bare လား envelope လား
  5. Error ကို သီးသန့် ကိုင်တွယ်

Body ကို ဖတ်တာက နောက်ဆုံးအဆင့်ပါ၊ အဲဒီမတိုင်ခင် status နဲ့ header တွေကသာ ဘယ်လို ဖတ်ရမလဲ ပြောပါတယ်။

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

text
HTTP/1.1 <status code> <reason phrase>
Content-Type: application/json; charset=utf-8
<other headers>

success : { ...resource }   or   { "data": ..., "meta": ... }
error   : { "error": { "code": "...", "message": "..." } }
204     : (no body, and no Content-Type)

Status line၊ header၊ လွတ်တဲ့ line၊ body ဆိုတဲ့ ပုံစံက response တိုင်းမှာ တူပါတယ်။ ကွာတာက body ရဲ့ ပုံစံပါ။

Worked example: ပုံစံငါးမျိုးကို parse() တစ်ခုနဲ့ ကိုင်ခြင်း

အောက်က script က server တစ်ခုကို စတင်ပြီး response ပုံစံမတူတဲ့ route ငါးခု ပြန်ပါတယ်: bare user၊ envelope နဲ့ list၊ 204၊ JSON error နဲ့ gateway ရဲ့ HTML page။ ပြီးတော့ parse() helper တစ်ခုက status၊ Content-Type၊ body ကို အစီအစဉ်တကျ စစ်ပြီး { status, data, error } ပုံစံတစ်ခုတည်းအဖြစ် ပြောင်းပေးပါတယ်။

Output ရဲ့ ပထမ line ကို အရင်ကြည့်ပါ: 204 response ကို တိုက်ရိုက် res.json() လုပ်ရင် ဘာ error တက်လဲ ပြပါတယ်။ ပြီးရင် parse() က ဒီ response တွေကို error မတက်ဘဲ ဘယ်လို ကိုင်သလဲ တွေ့ရပါမယ်။

response-shapes.mjs
import http from "node:http";

const alice = { id: "u_1", name: "Alice", nickname: null };

const server = http.createServer((req, res) => {
  const send = (status, body) => {
    if (body === undefined) {
      res.writeHead(status); // 204: no headers about a body, and no body
      return res.end();
    }
    res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
    res.end(JSON.stringify(body));
  };

  const route = `${req.method} ${req.url}`;
  if (route === "GET /users/u_1") return send(200, alice);
  if (route === "GET /users") {
    return send(200, { data: [{ id: "u_1", name: "Alice" }], meta: { total: 1 } });
  }
  if (route === "DELETE /users/u_1") return send(204);
  if (route === "GET /users/u_9") {
    const error = { code: "user_not_found", message: "No user with id u_9" };
    return send(404, { error });
  }
  // What a proxy or gateway may return instead of your API's JSON.
  res.writeHead(502, { "Content-Type": "text/html" });
  res.end("<html><body>Bad Gateway</body></html>");
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

// One place that turns any response into { status, data, error }.
async function parse(res) {
  if (res.status === 204) return { status: 204, data: null, error: null };
  const type = res.headers.get("content-type") ?? "";
  if (!type.includes("application/json")) {
    const text = await res.text();
    const error = { code: "not_json", message: text.slice(0, 22) };
    return { status: res.status, data: null, error };
  }
  const json = await res.json();
  if (!res.ok) return { status: res.status, data: null, error: json.error };
  return { status: res.status, data: json.data ?? json, error: null };
}

const gone = await fetch(`${base}/users/u_1`, { method: "DELETE" });
try {
  await gone.json();
} catch (err) {
  console.log("json() on a 204:", err.name, "-", err.message);
}

const calls = [
  ["GET", "/users/u_1"],
  ["GET", "/users"],
  ["DELETE", "/users/u_1"],
  ["GET", "/users/u_9"],
  ["GET", "/oops"],
];
for (const [method, path] of calls) {
  const result = await parse(await fetch(base + path, { method }));
  console.log(method.padEnd(6), path.padEnd(11), JSON.stringify(result));
}
server.close();

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

  1. Bare and envelopereturn send(200, { data: [{ id: "u_1", name: "Alice" }], meta: { total: 1 } });

    /users/u_1 က bare object ပြန်ပြီး /users က data နဲ့ meta ပါတဲ့ envelope ပြန်ပါတယ်။ ဒီ demo က နှစ်မျိုးလုံး ရှိနေတာကို parse() က ကိုင်နိုင်ကြောင်း ပြချင်လို့ ရောထားတာပါ၊ တကယ့် API မှာ တစ်ပုံစံတည်း ရွေးပါ။

  2. 204 has no bodyif (route === "DELETE /users/u_1") return send(204);

    send() က body မပါရင် writeHead(status) နဲ့ res.end() ပဲ လုပ်ပါတယ်၊ Content-Type မထည့်ပါဘူး။ ဒါက 204 ရဲ့ စံပုံစံပါ: အောင်မြင်ပြီး ပြောစရာ body မရှိပါဘူး။

  3. One error shapeconst error = { code: "user_not_found", message: "No user with id u_9" };

    Error က { error: { code, message } } ပုံစံပါ။ code ကို program က switch လုပ်လို့ရပြီး message ကို user ကို ပြလို့ရပါတယ်။ Endpoint တိုင်းမှာ ဒီပုံစံကိုပဲ သုံးရင် client မှာ error handling တစ်နေရာတည်း လိုပါတယ်။

  4. A gateway's HTMLres.writeHead(502, { "Content-Type": "text/html" });

    မသိတဲ့ route မှာ HTML ပြန်တာက proxy ဒါမှမဟုတ် load balancer က ပြတတ်တဲ့ 502 page ကို အတုယူထားတာပါ။ ကိုယ့် API ရဲ့ JSON မဟုတ်လို့ client က JSON လို့ မယူဆရပါဘူး။

  5. Check Content-Typeif (!type.includes("application/json")) {

    parse() က res.json() မခေါ်ခင် Content-Type ကို စစ်ပါတယ်။ JSON မဟုတ်ရင် res.text() နဲ့ ဖတ်ပြီး not_json error အဖြစ် ပြောင်းပေးတာမို့ SyntaxError မတက်ပါဘူး။

  6. Envelope or barereturn { status: res.status, data: json.data ?? json, error: null };

    json.data ရှိရင် envelope၊ မရှိရင် body တစ်ခုလုံးက resource ဆိုပြီး data ကို ရွေးပါတယ်။ အောင်မြင်တဲ့ ပုံစံတွေက ဒီတစ်ကြောင်းနဲ့ တူညီသွားပါတယ်။

  7. json() on a 204await gone.json();

    204 response ကို တိုက်ရိုက် json() လုပ်တဲ့ဒီ line က SyntaxError: Unexpected end of JSON input ကို ထုတ်ပြပါတယ်။ ဒါကြောင့် parse() က 204 ကို အရင်ဆုံး စစ်ပါတယ်။

You should see
json() on a 204: SyntaxError - Unexpected end of JSON input
GET    /users/u_1  {"status":200,"data":{"id":"u_1","name":"Alice","nickname":null},"error":null}
GET    /users      {"status":200,"data":[{"id":"u_1","name":"Alice"}],"error":null}
DELETE /users/u_1  {"status":204,"data":null,"error":null}
GET    /users/u_9  {"status":404,"data":null,"error":{"code":"user_not_found","message":"No user with id u_9"}}
GET    /oops       {"status":502,"data":null,"error":{"code":"not_json","message":"<html><body>Bad Gatewa"}}

Envelope လား bare resource လား

ပုံစံပုံသဏ္ဍာန်အားသာချက် / အားနည်းချက်
Bare resource{ "id": "u_1", "name": "Alice" }ရိုးရှင်း၊ ဒါပေမဲ့ list မှာ meta ထည့်စရာ နေရာ မရှိ
Envelope{ "data": {...}, "meta": {...} }Pagination၊ link ထည့်ဖို့ နေရာရှိ၊ ဒါပေမဲ့ အလွှာတစ်ထပ် ပိုရှည်
success flag ပါတဲ့ envelope{ "success": true, "data": ..., "error": null }Status code နဲ့ ထပ်နေပြီး မကိုက်ညီနိုင်

တတိယပုံစံကို သင်ခန်းစာတွေမှာ မကြာခဏ တွေ့ရပေမဲ့ success: true ပြောနေတဲ့ response က HTTP status 500 နဲ့ ပြန်လာရင် client က ဘယ်ဟာကို ယုံရမလဲ မသိတော့ပါဘူး။ Status code ကို အမှန်တရားရဲ့ တစ်နေရာတည်း ထားပါ။ Meta ထည့်စရာ မလိုတဲ့ API ငယ်လေးတွေမှာ bare resource က လုံလောက်ပါတယ်၊ list နဲ့ pagination ရှိတဲ့ API တွေမှာတော့ envelope ကို အစကတည်းက ရွေးထားတာ ကောင်းပါတယ်၊ နောက်မှ ပြောင်းရင် client အားလုံး ပြင်ရလို့ပါ။

Number, null နဲ့ မပါတဲ့ field

JSON မှာ number က JavaScript ရဲ့ double ဖြစ်သွားလို့ 2^53 - 1 (9007199254740991) ထက် ကြီးတဲ့ integer ကို တိတိကျကျ မသိမ်းနိုင်ပါဘူး။ ID ကြီးတွေကို string အဖြစ် ပို့ပါ။ null က 'ရှိပေမဲ့ အလွတ်' ကို ပြောပြီး field မပါတာက 'ဒီနေရာမှာ မသက်ဆိုင် ဒါမှမဟုတ် မသိ' ကို ပြောတာပါ။ JSON.stringify က undefined ကို ဖယ်ထုတ်ပေမဲ့ null ကို ထိန်းထားပါတယ်။

numbers-and-nulls.mjs
const raw = '{"id": 9007199254740993, "idText": "9007199254740993", "nickname": null}';
const user = JSON.parse(raw);

// A number above 2^53 - 1 silently loses precision; a string keeps every digit.
console.log(user.id, Number.isSafeInteger(user.id));
console.log(user.idText);

// null means "known to be empty"; a missing field is simply not there.
console.log("nickname" in user, user.nickname);
console.log("email" in user, user.email);

// JSON.stringify drops undefined but keeps null.
console.log(JSON.stringify({ a: undefined, b: null }));

ပထမ line မှာ id 9007199254740993 က 9007199254740992 ဖြစ်သွားပြီး isSafeInteger က false ပါ၊ string version ကတော့ ဂဏန်းအားလုံး ကျန်ပါတယ်။ နောက်နှစ်ကြောင်းက nickname: null မှာ field ရှိပြီး email မှာ မရှိတာကို ပြပါတယ်။ နောက်ဆုံး line က stringify မှာ a မပါတော့ပေမဲ့ b: null ကျန်တာကို ပြပါတယ်။ ဒါကြောင့် 'မသိ' နဲ့ 'အလွတ်' ကို API မှာ မရောပါနဲ့၊ documentation မှာ ရေးထားပါ။

JSON မဟုတ်တဲ့ body ကို json() လုပ်ရင်

Gateway ရဲ့ HTML page ကို res.json() လုပ်ကြည့်ရင် ဘာတက်လဲ အောက်မှာ ပြထားပါတယ်။ Node 22 ရဲ့ error စာသားက ပြဿနာဖြစ်တဲ့ အစကို ပါပြပေးတာမို့ ဖတ်ရင် HTML ရောက်လာတာ ချက်ချင်း သိနိုင်ပါတယ်။

json-on-html.mjs
const gatewayPage = new Response("<html>Bad Gateway</html>", {
  status: 502,
  headers: { "Content-Type": "text/html" },
});

console.log(gatewayPage.headers.get("content-type"));
try {
  await gatewayPage.json();
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}

ပထမ line က Content-Type ကို ပြပြီး ဒုတိယ line က SyntaxError ပါ။ Content-Type ကို အရင်စစ်ထားရင် ဒီ error မတက်ဘဲ 'gateway က HTML ပြန်တယ်' ဆိုတဲ့ အကျိုးရှိတဲ့ error ကို ကိုယ်တိုင် ဖန်တီးပေးလို့ရပါတယ်။

Error shape: problem details

ကိုယ်ပိုင် error ပုံစံ ဖန်တီးမယ့်အစား RFC 9457 (Problem Details for HTTP APIs) ကို သုံးလို့ရပါတယ်။ Content-Type က application/problem+json ဖြစ်ပြီး type, title, status, detail ဆိုတဲ့ စံ field တွေ ပါပါတယ်၊ ကိုယ်ပိုင် field (errors လို) ကို ထပ်ထည့်လို့ရပါတယ်။ ဒါက မဖြစ်မနေ မဟုတ်ပါဘူး၊ ဒါပေမဲ့ client library တွေက သိတဲ့ ပုံစံမို့ စဉ်းစားထိုက်ပါတယ်။

text
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation",
  "title": "Validation failed",
  "status": 422,
  "detail": "email must be a valid address",
  "errors": [{ "field": "email", "message": "invalid format" }]
}

422 ကို အရင် documentation တွေမှာ Unprocessable Entity လို့ ခေါ်ပါတယ်၊ နာမည်ပြောင်းသွားပေမဲ့ code တူပါတယ်။ ဒီ example ထဲက api.example.com က ဥပမာ host သက်သက်ပါ။

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

လက်တွေ့ project တွေမှာ response ဖတ်ခြင်း

လက်တွေ့ frontend ဒါမှမဟုတ် backend project တွေမှာ response ကို ဖတ်တဲ့ code ကို နေရာတစ်ခုတည်း (api client helper) မှာ စုထားပါတယ်။ ဒါမှ status စစ်တာ၊ Content-Type စစ်တာ၊ error shape ကို ကိုင်တာ၊ 401 မှာ login ပြန်ခိုင်းတာတွေကို endpoint တိုင်းမှာ ပြန်မရေးရပါဘူး။ Monitoring ကလည်း status class အလိုက် 4xx နဲ့ 5xx ကို ခွဲတွက်လို့ client အမှားနဲ့ server အမှားကို ကွဲကွဲပြားပြား မြင်ရပါတယ်။

  • OpenAPI documentation နဲ့ client generator တွေက response ပုံစံ တစ်ပုံစံတည်း ဖြစ်မှ type တွေကို မှန်ကန်စွာ ထုတ်ပေးနိုင်ပါတယ်။
  • Rate limit ကျတဲ့အခါ 429 နဲ့ Retry-After header ကို ပြန်ပြီး client က အဲဒီ စက္ကန့်အရေအတွက် စောင့်ပါတယ်။
  • ETag နဲ့ Cache-Control header တွေက client နဲ့ CDN ကို data ကို cache လုပ်လို့ရလား ပြောပါတယ်၊ 304 Not Modified ကလည်း body မပါဘဲ ပြန်ပါတယ်။
  • X-Request-Id လို header တစ်ခုကို response တိုင်းမှာ ထည့်ထားရင် user က ပြဿနာ report လုပ်တဲ့အခါ server log ထဲက request ကို တန်းရှာလို့ရပါတယ်။

အမှားများ

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

204 ဒါမှမဟုတ် HTML ကို res.json() လုပ်ခြင်း

204 မှာ body မရှိလို့ Unexpected end of JSON input၊ gateway ရဲ့ HTML မှာ Unexpected token '<' ဆိုတဲ့ SyntaxError တွေ တက်ပါတယ်။ Status နဲ့ Content-Type ကို အရင်စစ်ပါ။

အမှားကို 200 OK နဲ့ ပြန်ခြင်း

{ "success": false } ကို 200 နဲ့ ပြန်ရင် res.ok ကို စစ်တဲ့ client၊ cache၊ monitoring တွေက အောင်မြင်တယ်လို့ ယူဆပါတယ်။ အမှားကို အမှန်တကယ် 4xx ဒါမှမဟုတ် 5xx နဲ့ ပြန်ပါ။

Endpoint တစ်ခုချင်းစီမှာ error ပုံစံ မတူခြင်း

တစ်နေရာက { error: 'x' }၊ နောက်တစ်နေရာက { message: 'y' }၊ ထပ်တစ်နေရာက plain text ဆိုရင် client မှာ error ကို ခွဲဖတ်တဲ့ branch တွေ ပွားလာပါတယ်။ Error ပုံစံတစ်ခုကို ဆုံးဖြတ်ပြီး middleware တစ်ခုက ထုတ်ပေးပါ။

ID ကြီးတွေကို number အဖြစ် ပို့ခြင်း

9007199254740993 လို ID ကို JSON number အဖြစ် ပို့ပြီး JavaScript client က ဖတ်ရင် 9007199254740992 ဖြစ်သွားပါတယ်၊ မှားနေတဲ့ record ကို တိတ်တဆိတ် ညွှန်နေပါတယ်။ ID တွေကို string အဖြစ် ပို့ပါ။

Best Practices

Best practices

  • Status → Content-Type → body ဆိုတဲ့ အစီအစဉ်နဲ့ ဖတ်ပြီး ဒီအစီအစဉ်ကို helper တစ်ခုထဲမှာ စုပါ။
  • API တစ်ခုလုံးမှာ success ပုံစံတစ်ခုနဲ့ error ပုံစံတစ်ခုကိုသာ သုံးပါ၊ status code ကို အမှန်ကို ပြောတဲ့ တစ်ခုတည်းသော နေရာအဖြစ် ထားပါ။
  • Error response ထဲ stack trace၊ SQL၊ internal host နာမည်တွေ မထည့်ပါနဲ့၊ server log မှာပဲ မှတ်ပါ။
  • ID ကြီးတွေကို string နဲ့ ပို့ပြီး null နဲ့ မပါတဲ့ field ကို ဘာကွာလဲ documentation မှာ ရေးပါ။

Mini challenge

Mini challenge: error ပုံစံတစ်ခုတည်းရှိတဲ့ products API

/products API တစ်ခုရေးပါ၊ အောင်မြင်တဲ့ response တိုင်းက { data } (list မှာ meta.total လည်းပါ)၊ error တိုင်းက { error: { code, message } } ပုံစံ ဖြစ်ရမယ်။ DELETE က 204 နဲ့ body မပါဘဲ ပြန်ရမယ်၊ မသိတဲ့ route က 404၊ မထောက်ပံ့တဲ့ method က 405 ဖြစ်ရမယ်။ route တစ်ခုက error ကို throw လုပ်တဲ့အခါ အဲဒီ အသေးစိတ်ကို client ကို မပြဘဲ server log ထဲမှာပဲ မှတ်ပြီး 500 ကို ယေဘုယျ message နဲ့ ပြန်ပါ။

  • sendJson နဲ့ fail helper နှစ်ခုကို သုံးပြီး ပုံစံတစ်ခုတည်း ထုတ်ရမယ်
  • DELETE ကို 204 နဲ့ Content-Type မပါ၊ body မပါဘဲ ပြန်ရမယ်
  • Throw ဖြစ်တဲ့ route ကို catch လုပ်ပြီး err.message ကို serverLog ထဲ ထည့်ကာ client ကို internal_error ပြန်ရမယ်
  • URL ခြောက်ခုကို ခေါ်ပြီး status နဲ့ body (သို့မဟုတ် (no body)) ကို print ထုတ်ကာ server log ကိုပါ ပြပါ
products-api.mjs
import http from "node:http";

// TODO: a products array and a serverLog array

// TODO: sendJson(res, status, body) and fail(res, status, code, message)
//   every success is { data: ... } (lists also get meta: { total })
//   every error is { error: { code, message } }

// TODO: a server (port 0) handling
//   GET /products, GET /products/<id>, DELETE /products/<id> (204, no body),
//   unknown routes (404), unsupported methods (405)
//   plus a route that throws: catch it, push err.message onto serverLog,
//   and answer 500 with a generic message that does not reveal the details

// TODO: call six URLs with fetch, print "<method> <path> <status> <body or (no body)>",
//       then print the server log and close the server

ရလဒ်: GET /products က data နဲ့ meta ပါတဲ့ 200၊ /products/p_1 က { data } 200၊ /products/p_9 က product_not_found 404၊ /products/boom က internal_error 500၊ DELETE က 204 (no body)၊ /nowhere က route_not_found 404 ဖြစ်ပြီး server log မှာ ECONNREFUSED စာသား ရှိရမယ်။

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

Request handler တစ်ခုလုံးကို try/catch ထဲ ထည့်ပါ၊ catch ထဲမှာ serverLog.push(err.message) လုပ်ပြီး fail(res, 500, ...) ကို ခေါ်ပါ။ 204 အတွက် res.writeHead(204) နဲ့ res.end() ကိုပဲ သုံးပါ၊ sendJson မသုံးပါနဲ့။ req.url.split('/') နဲ့ resource နဲ့ id ကို ခွဲယူနိုင်ပါတယ်။

အဖြေ ကြည့်ရန်
products-api.mjs
import http from "node:http";

const products = [{ id: "p_1", name: "Keyboard", price: 49 }];
const serverLog = [];

function sendJson(res, status, body) {
  res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
  res.end(JSON.stringify(body));
}
function fail(res, status, code, message) {
  sendJson(res, status, { error: { code, message } });
}

const server = http.createServer((req, res) => {
  try {
    const [, resource, id] = req.url.split("/");
    if (resource !== "products") {
      return fail(res, 404, "route_not_found", "No such route");
    }

    if (req.method === "GET" && id === undefined) {
      return sendJson(res, 200, { data: products, meta: { total: products.length } });
    }
    if (req.method === "GET" && id === "boom") {
      throw new Error("connect ECONNREFUSED db.internal:5432");
    }
    if (req.method === "GET") {
      const product = products.find((p) => p.id === id);
      if (!product) return fail(res, 404, "product_not_found", `No product ${id}`);
      return sendJson(res, 200, { data: product });
    }
    if (req.method === "DELETE") {
      res.writeHead(204);
      return res.end();
    }
    return fail(res, 405, "method_not_allowed", `${req.method} is not supported`);
  } catch (err) {
    serverLog.push(err.message); // the details stay on the server
    return fail(res, 500, "internal_error", "Something went wrong");
  }
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

for (const [method, path] of [
  ["GET", "/products"],
  ["GET", "/products/p_1"],
  ["GET", "/products/p_9"],
  ["GET", "/products/boom"],
  ["DELETE", "/products/p_1"],
  ["GET", "/nowhere"],
]) {
  const res = await fetch(base + path, { method });
  const text = await res.text();
  console.log(`${method} ${path}`.padEnd(22), res.status, text || "(no body)");
}
console.log("server log:", serverLog.join(" | "));
server.close();

Quick Quiz 1 / 3

DELETE က 204 No Content ပြန်တယ်။ await res.json() က ဘာလုပ်လဲ?

Quick Quiz 2 / 3

Gateway က 502 နဲ့ HTML page ပြန်တယ်။ res.json() မခေါ်ခင် ဘာကို စစ်သင့်လဲ?

Quick Quiz 3 / 3

Missing user အတွက် API က 200 OK နဲ့ { "success": false, "error": "Not found" } ပြန်တယ်။ အဓိက ပြဿနာက ဘာလဲ?

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

  • Response ကို status → Content-Type → body အစီအစဉ်နဲ့ ဖတ်ပါ၊ 2xx အောင်မြင်၊ 4xx client အမှား၊ 5xx server အမှား။
  • 204 မှာ body မပါလို့ res.json() က SyntaxError ပေးပြီး gateway ရဲ့ HTML ကိုလည်း Content-Type မစစ်ဘဲ parse လုပ်လို့ မရပါဘူး။
  • API တစ်ခုလုံးမှာ success ပုံစံ (bare ဒါမှမဟုတ် envelope) နဲ့ { error: { code, message } } ပုံစံကို တစ်မျိုးတည်း ထားပါ။
  • ID ကြီးတွေကို string အဖြစ် ပို့ပါ၊ null နဲ့ မပါတဲ့ field ကို ခွဲပါ၊ error ထဲ ထိခိုက်လွယ်တဲ့ အသေးစိတ် မထည့်ပါနဲ့။

RFC 9110 — HTTP Semantics — IETF

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

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

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

Response Shape & Status Codes | Thuta Learning