Thuta Learning
JavaScript
IntermediateProgrammingအခြေခံ

Error Types

JavaScriptသင်ခန်းစာ 2125 မိနစ်

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

  • Error message တစ်ခုကို ဖတ်ပြီး built-in error type လေးမျိုးထဲက ဘယ်ဟာလဲ ခွဲခြားနိုင်ဖို့
  • Error object ရဲ့ name, message, stack, cause property တွေကို အသုံးချနိုင်ဖို့
  • Error ကို extends လုပ်ပြီး name နဲ့ field အပိုတွေပါတဲ့ custom error class ရေးနိုင်ဖို့
  • instanceof နဲ့ error type အလိုက် ကွဲပြားစွာ တုံ့ပြန်ပြီး operational error နဲ့ programmer bug ကို ခွဲခြားနိုင်ဖို့

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

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

ဆေးရုံ အရေးပေါ်ဌာနမှာ လူနာ ရောက်လာရင် "နေမကောင်းဘူး" လို့ပဲ မှတ်လို့ မရပါဘူး။ အရိုးကျိုးလား၊ အပူလောင်လား၊ အဆိပ်သင့်လားဆိုတာ ခွဲပြီးမှ မှန်ကန်တဲ့ ဆရာဝန်ဆီ ပို့လို့ရပါတယ်။ Error type တွေကလည်း အဲဒီလို အမျိုးအစား တံဆိပ်တွေပါ — ပြဿနာ ဘာလဲ ဆိုတာကို name တစ်လုံးတည်းနဲ့ ပြောပြပါတယ်။

JavaScript က ကြေညာမထားတဲ့ variable ကို သုံးရင် ReferenceError၊ null ပေါ်က property ဖတ်ရင် TypeError လို type တစ်ခုစီနဲ့ error ပစ်ပါတယ်။ ကိုယ့် app အတွက်လည်း "input မမှန်ဘူး" ဆိုရင် ValidationError၊ "ရှာမတွေ့ဘူး" ဆိုရင် NotFoundError လို တံဆိပ်အသစ်တွေ ကိုယ်တိုင် ဖန်တီးလို့ရပါတယ်။

Problem → Why → Solution

ပြဿနာ: string ပစ်ပြီး message ကို စစ်တော့ catch ထဲမှာပဲ crash ဖြစ်တယ်

withdraw() က Error object အစား "Insufficient funds" ဆိုတဲ့ string ကို throw လုပ်ပါတယ်။ Caller က error.message ထဲမှာ "funds" ပါလား စစ်ဖို့ ကြိုးစားပေမယ့် string မှာ message property မရှိလို့ undefined.includes() ကို ခေါ်မိပြီး catch block ထဲမှာပဲ TypeError အသစ် တက်ပါတယ်။ Error ကို ကိုင်တွယ်ဖို့ ရေးထားတဲ့ code ကိုယ်တိုင်က crash ဖြစ်သွားတာပါ။

withdraw.js
function withdraw(balance, amount) {
  if (amount > balance) throw "Insufficient funds"; // a string, not an Error
  return balance - amount;
}

try {
  withdraw(100, 500);
} catch (error) {
  if (error.message.includes("funds")) {   // error.message is undefined
    console.log("Please top up your account");
  }
}
// TypeError: Cannot read properties of undefined (reading 'includes')

ဘာကြောင့် ဒီလို ဖြစ်တာလဲ

JavaScript က ဘယ် value ကိုမဆို throw လုပ်ခွင့်ပေးပေမယ့် Error object မှာပဲ name, message, stack ပါပါတယ်။ String ပစ်ရင် stack trace လည်း မရဘဲ caller ဘက်က ယုံကြည်စိတ်ချစွာ စစ်လို့ မရပါဘူး။ Message စာသားကို စစ်တာကလည်း စာသား နည်းနည်း ပြောင်းတာနဲ့ ကျိုးပါတယ်။ InsufficientFundsError လို type သတ်မှတ်ပြီး instanceof နဲ့ စစ်ရင် ဒီပြဿနာ နှစ်ခုလုံး ပြေလည်ပါတယ်။

Core concept: built-in error type တွေနဲ့ custom error

Error object တိုင်းမှာ name (error အမျိုးအစား)၊ message (လူဖတ်ဖို့ ရှင်းလင်းချက်)၊ stack (error ဖြစ်တဲ့ function call လမ်းကြောင်း) ပါပြီး new Error(message, { cause }) နဲ့ ဖန်တီးရင် cause (မူရင်း error) ပါ ပါပါတယ်။ Built-in error type တွေ အားလုံးက Error ကနေ အမွေဆက်ခံထားလို့ error instanceof Error က အမြဲ true ပါ။

Typeဘယ်အချိန် တက်လဲဥပမာ
SyntaxErrorCode ဒါမှမဟုတ် data ရဲ့ ပုံစံ မမှန်ရင်JSON.parse("{bad}")
ReferenceErrorမရှိတဲ့ variable နာမည်ကို သုံးရင်console.log(missingName)
TypeErrorValue ကို သူ့ type က ခွင့်မပြုတဲ့ ပုံစံနဲ့ သုံးရင်null.toString(), 5()
RangeErrorNumber က ခွင့်ပြုထားတဲ့ အပိုင်းအခြား ကျော်ရင်new Array(-1), (1.5).toFixed(200)

ဒီလေးမျိုးအပြင် decodeURIComponent("%") လို URI မမှန်ရင် URIError နဲ့ Promise.any() က promise အားလုံး fail ဖြစ်ရင် error အများကြီးကို စုပေးတဲ့ AggregateError လည်း ရှိပါတယ်။ ကိုယ့် app ရဲ့ domain failure တွေအတွက်တော့ class ValidationError extends Error လို custom class ရေးပြီး constructor ထဲမှာ this.name ကို သတ်မှတ်ပါ။ မသတ်မှတ်ရင် Error.prototype ကနေ name = "Error" ကို အမွေရလို့ log ထဲမှာ ဘယ် error လဲ ခွဲမရပါဘူး။ field, code လို အသုံးဝင်တဲ့ အချက်အလက် အပိုတွေကိုလည်း property အဖြစ် ထည့်လို့ရပါတယ်။

Error တွေကို အုပ်စုနှစ်ခု ခွဲစဉ်းစားပါ။ Operational error က input မမှန်တာ၊ network ပြတ်တာလို program မှန်နေပေမယ့် ကြိုမြင်ထားရမယ့် ပြဿနာ ဖြစ်ပြီး user ကို ရှင်းပြတာ၊ retry လုပ်တာနဲ့ ကိုင်တွယ်ပါတယ်။ Programmer bug ကတော့ undefined ပေါ်က property ဖတ်တဲ့ TypeError လို code ကိုယ်တိုင် မှားနေတာဖြစ်လို့ ဖုံးမထားဘဲ log ထုတ်ပြီး code ကို ပြင်ရပါတယ်။ Custom error type တွေက ဒီ ခွဲခြားမှုကို လွယ်စေပါတယ် — AppError မိသားစုထဲက error ဆိုရင် operational ဖြစ်ပြီး ကျန်တာ အားလုံးကို bug လို့ ယူဆလို့ရပါတယ်။

မှတ်ထားရမယ့် ပုံစံ
  1. Error object ကို throw
  2. catch မှာ instanceof နဲ့ type စစ်
  3. သိတဲ့ type ဆို ကိုင်တွယ်
  4. မသိတဲ့ type ဆို rethrow

Message စာသားက လူအတွက်၊ type နဲ့ code က program အတွက်ပါ။

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

javascript
class CustomError extends Error {
  constructor(message, extraInfo, options) {
    super(message, options);     // options may hold { cause }
    this.name = "CustomError";
    this.extraInfo = extraInfo;
  }
}

try { riskyOperation(); } catch (error) {
  if (error instanceof CustomError) handleKnownProblem(error);
  else throw error;
}

super(message, options) က message နဲ့ cause ကို Error ဆီ ပေးပြီး this.name က log နဲ့ stack မှာ ပေါ်မယ့် နာမည်ပါ။ catch ထဲမှာ instanceof နဲ့ သိတဲ့ type ကိုပဲ ကိုင်တွယ်ပြီး ကျန်တာ ပြန်ပစ်ပါတယ်။

Example: built-in error သုံးမျိုးနဲ့ ValidationError

အပိုင်း သုံးခုက built-in error တစ်မျိုးစီကို တမင် ဖြစ်စေပြီး name နဲ့ message ကို print ထုတ်ပါတယ်။ Message တိုင်းကို ကိုယ်တိုင် ရေးထားတဲ့ string ကနေ မဟုတ်ဘဲ error.message အစစ်ကနေ print ထုတ်ထားလို့ engine တကယ်ပြောတာကို မြင်ရပါတယ်။ Message စာသားတွေက JavaScript engine အလိုက် ကွာနိုင်ပါတယ် — ဒီ output က Node.js (V8) ကပါ၊ Firefox မှာ စာသား ကွာပါမယ်။ ဒါကြောင့် program logic မှာ message ကို မစစ်ဘဲ type ကိုပဲ စစ်ရတာပါ။

error-types.js
// Three built-in error types
function demonstrateErrors() {
  // 1. ReferenceError: a name that was never declared
  try {
    console.log(undefinedVariable);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }

  // 2. TypeError: using a value in a way its type does not allow
  try {
    null.toString();
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }

  // 3. RangeError: a number outside the allowed range
  try {
    new Array(-1);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

demonstrateErrors();

// A custom error type
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function validateAge(age) {
  if (age < 0 || age > 120) {
    throw new ValidationError("Age must be between 0 and 120", "age");
  }
  return `Valid age: ${age}`;
}

try {
  console.log(validateAge(25));
  console.log(validateAge(150));
} catch (error) {
  console.log(`${error.name} (${error.field}): ${error.message}`);
  console.log(error instanceof ValidationError, error instanceof Error);
}

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

  1. Line 12null.toString();

    null မှာ property လုံးဝ မရှိလို့ method ခေါ်ရင် TypeError ပါ။ API response ထဲက field တစ်ခု null ဖြစ်နေတဲ့အခါ လက်တွေ့မှာ အဖြစ်အများဆုံး error ပါ။

  2. Line 19new Array(-1);

    Array ရဲ့ length က အနုတ် မဖြစ်နိုင်လို့ RangeError ပါ။ Type (number) က မှန်ပေမယ့် value က ခွင့်ပြုထားတဲ့ အပိုင်းအခြား အပြင်ဘက်မှာ ရှိနေတာပါ။

  3. Lines 28-34class ValidationError extends Error {

    Error ကို extends လုပ်ပြီး super(message) နဲ့ message ကို ပေးကာ this.name ကို ကိုယ်တိုင် သတ်မှတ်ပါတယ်။ field ဆိုတဲ့ property အပိုက ဘယ် input field မှားလဲ UI ကို ပြောပြပေးနိုင်ပါတယ်။

  4. Line 38throw new ValidationError("Age must be between 0 and 120", "age");

    Business rule ချိုးဖောက်တဲ့အခါ ရိုးရိုး Error မဟုတ်ဘဲ ValidationError ကို ပစ်လို့ caller က အမျိုးအစားနဲ့ ခွဲခြားနိုင်ပါတယ်။

  5. Line 48console.log(error instanceof ValidationError, error instanceof Error);

    Custom error က ValidationError ရော Error ရဲ့ instance ပါ ဖြစ်လို့ true true ရပါတယ်။ ဒါကြောင့် "Error အားလုံး" ကို ဖမ်းတဲ့ code ကလည်း custom error ကို ဆက်ကိုင်တွယ်နိုင်ပါတယ်။

You should see
ReferenceError: undefinedVariable is not defined
TypeError: Cannot read properties of null (reading 'toString')
RangeError: Invalid array length
Valid age: 25
ValidationError (age): Age must be between 0 and 120
true true

Custom error hierarchy နဲ့ cause

App ကြီးလာရင် AppError ဆိုတဲ့ base class တစ်ခုထားပြီး ValidationError, NotFoundError တို့က အဲဒါကို extends လုပ်ပါတယ်။ this.name = this.constructor.name လို့ base မှာ တစ်ခါရေးရင် subclass တိုင်းက ကိုယ့် class နာမည်ကို အလိုအလျောက် ရပါတယ်။ options ကို super() ဆီ လက်ဆင့်ကမ်းရင် cause လည်း အလုပ်လုပ်ပါတယ်။

app-errors.js
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = this.constructor.name;
  }
}
class NotFoundError extends AppError {}

const dbError = new Error("connection reset");
const err = new NotFoundError("Order 42 not found", { cause: dbError });
console.log(err.name);          // NotFoundError
console.log(err.cause.message); // connection reset
console.log(err instanceof AppError); // true

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

Real project တွေမှာ ဘယ်လို သုံးလဲ

REST API server တစ်ခုမှာ service code က ValidationError, NotFoundError, AuthError လို custom error တွေ ပစ်ပြီး error-handling middleware တစ်နေရာတည်းက instanceof နဲ့ 400, 404, 401 status code တွေကို map လုပ်ပါတယ်။ မသိတဲ့ error ဆိုရင်တော့ 500 နဲ့ "Something went wrong" လို ယေဘုယျ message ကိုပဲ user ကို ပြပြီး stack trace အပြည့်ကို server log ထဲမှာပဲ ရေးပါတယ်။ ဒါမှ database password လို internal အချက်အလက် ပေါက်မကြားပါဘူး။

Frontend မှာလည်း form validation library တွေက field နာမည်ပါတဲ့ error object တွေကို ပြန်ပေးလို့ input တစ်ခုချင်းအောက်မှာ message ပြနိုင်ပါတယ်။ Monitoring tool တွေက error ကို name အလိုက် အုပ်စုဖွဲ့ပြလို့ custom error တွေမှာ name မှန်မှန် ပေးထားရင် "ဒီအပတ် ValidationError ဘယ်နှစ်ခု၊ TypeError ဘယ်နှစ်ခု" ဆိုတာ ချက်ချင်း မြင်ရပါတယ်။ TypeError များလာရင် programmer bug ရှိနေတဲ့ လက္ခဏာပါ။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. Custom error မှာ this.name မသတ်မှတ်တာ

class DbError extends Error {} လို့ပဲ ရေးရင် new DbError("timeout").name က "Error" ဖြစ်နေပြီး log ထဲမှာ "Error: timeout" လို့ပဲ ပေါ်ပါတယ်။ instanceof ကတော့ အလုပ်လုပ်ပေမယ့် log ဖတ်တဲ့သူက ဘယ် error လဲ မသိနိုင်ပါဘူး။ Constructor ထဲမှာ this.name ကို သတ်မှတ်ပါ ဒါမှမဟုတ် base class မှာ this.constructor.name ကို သုံးပါ။

2. Error message စာသားကို စစ်ပြီး branch လုပ်တာ

if (error.message === "Cannot read properties of null (reading 'toString')") လို စစ်တာက browser တစ်ခုနဲ့ တစ်ခု၊ Node version တစ်ခုနဲ့ တစ်ခု စာသား ကွာတာနဲ့ ကျိုးပါတယ်။ ကိုယ့် custom error တွေရဲ့ message ကိုလည်း ပြင်ရေးချင်တဲ့အခါ logic ကို မထိခိုက်သင့်ပါဘူး။ instanceof ဒါမှမဟုတ် error.code လို တည်ငြိမ်တဲ့ property ကို စစ်ပါ။

3. Programmer bug ကို operational error လို ဖုံးထားတာ

catch (error) { return { status: 400, body: "Invalid request" }; } လို error အားလုံးကို 400 ပြန်ပေးရင် ကိုယ့် code ထဲက TypeError ကိုပါ user ရဲ့ request မှားတယ်လို့ ပြောမိပြီး bug ကို ဘယ်တော့မှ မတွေ့ရပါဘူး။ သိတဲ့ custom error type တွေကိုပဲ 4xx နဲ့ map လုပ်ပြီး ကျန်တာကို 500 အဖြစ် log ထုတ်ပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • App တစ်ခုလုံးအတွက် AppError base class တစ်ခု ထားပြီး domain error တွေကို အဲဒီကနေ extends လုပ်ပါ။
  • Error message ကို developer ဖတ်ဖို့ ရေးပြီး user ကို ပြမယ့် စာသားကို သီးခြား ထုတ်ပေးပါ။
  • Low-level error ကို high-level error အဖြစ် ပြောင်းတဲ့အခါ { cause } နဲ့ မူရင်းကို အမြဲ ချိတ်ထားပါ။
  • Built-in TypeError ဒါမှမဟုတ် RangeError ကို ကိုယ်တိုင် throw လုပ်တာလည်း မှန်ပါတယ် — argument type မှားရင် TypeError က အဓိပ္ပာယ် အရှင်းဆုံးပါ။

Mini challenge

Mini challenge: error ကို HTTP response အဖြစ် ပြောင်းပါ

AppError base class နဲ့ ValidationError, NotFoundError subclass နှစ်ခု ရေးပြီး error တစ်ခုကို HTTP status နဲ့ user အတွက် လုံခြုံတဲ့ message အဖြစ် ပြောင်းပေးတဲ့ toResponse() ကို ရေးပါ။

  • AppError က this.name ကို this.constructor.name နဲ့ သတ်မှတ်ပြီး options (cause) ကို super() ဆီ ပေးရမယ်
  • findUser(id) က integer မဟုတ်ရင် ValidationError၊ id 1 မဟုတ်ရင် NotFoundError ပစ်ရမယ်
  • toResponse(error) က ValidationError → 400၊ NotFoundError → 404၊ ကျန်တာ → 500 နဲ့ "Something went wrong" ပြန်ပေးရမယ်
  • id 1, "abc", 7 နဲ့ TypeError တစ်ခုကို စမ်းပြီး ရလဒ်တွေကို print ထုတ်ရမယ်
http-errors.js
class AppError extends Error {
  constructor(message, options) {
    // TODO: call super and set this.name from the class name
  }
}
// TODO: ValidationError and NotFoundError, both extending AppError

function findUser(id) {
  // TODO: ValidationError for non-integers, NotFoundError unless id is 1
  // TODO: otherwise return { id, name: "Su Su" }
}

function toResponse(error) {
  // TODO: 400 / 404 for the known types, 500 with a generic body otherwise
}

// TODO: for ids 1, "abc" and 7, print "200 <name>" or "<status> <body>"
// TODO: print the body toResponse gives for a plain TypeError

ရလဒ်: Console မှာ လေးကြောင်း ထွက်ရပါမယ်: 200 Su Su 400 Invalid id: abc 404 User 7 not found Something went wrong

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

Number.isInteger("abc") က false ပါ။ Subclass တွေမှာ constructor မရေးလည်း AppError ရဲ့ constructor ကို အမွေရလို့ this.constructor.name က "ValidationError" ဖြစ်ပါတယ်။ toResponse() မှာ instanceof check တွေကို subclass ကနေ အရင် စစ်ပါ။

အဖြေ ကြည့်ရန်
http-errors.js
class AppError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = this.constructor.name;
  }
}
class ValidationError extends AppError {}
class NotFoundError extends AppError {}

function findUser(id) {
  if (!Number.isInteger(id)) throw new ValidationError(`Invalid id: ${id}`);
  if (id !== 1) throw new NotFoundError(`User ${id} not found`);
  return { id, name: "Su Su" };
}

function toResponse(error) {
  if (error instanceof ValidationError) return { status: 400, body: error.message };
  if (error instanceof NotFoundError) return { status: 404, body: error.message };
  return { status: 500, body: "Something went wrong" };
}

for (const id of [1, "abc", 7]) {
  try {
    console.log(200, findUser(id).name);
  } catch (error) {
    const { status, body } = toResponse(error);
    console.log(status, body);
  }
}
console.log(toResponse(new TypeError("x is undefined")).body);

Quick Quiz 1 / 3

const user = undefined; console.log(user.name); က ဘယ် error type ကို ပစ်မလဲ။

Quick Quiz 2 / 3

try { throw "failed"; } catch (error) { console.log(error.stack); } က ဘာ print ထုတ်မလဲ။

Quick Quiz 3 / 3

class DbError extends Error {} လို့ပဲ ရေးထားရင် new DbError("timeout").name က ဘာလဲ။

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

  • Error object တွေမှာ name, message, stack (နဲ့ cause) ပါလို့ string မဟုတ်ဘဲ Error ကိုပဲ throw လုပ်ပါ။
  • ReferenceError = နာမည်မရှိ၊ TypeError = type မကိုက်၊ RangeError = အပိုင်းအခြားကျော်၊ SyntaxError = ပုံစံမမှန် ပါ။
  • Domain failure တွေအတွက် Error ကို extends လုပ်ပြီး this.name သတ်မှတ်ထားတဲ့ custom class ရေးပါ။
  • catch ထဲမှာ message စာသား မဟုတ်ဘဲ instanceof/code နဲ့ စစ်ပြီး programmer bug တွေကို ဖုံးမထားပါနဲ့။

MDN — JavaScript Guide — MDN Web Docs

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

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

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

Error Types | Thuta Learning