TypeScript จัดการข้อผิดพลาด



custom error — extends Error

class ValidationError extends Error {
  constructor(
    public readonly field: string,
    message: string,
  ) {
    super(message);
    this.name = "ValidationError";   // สำคัญ — ไม่งั้นเป็น "Error"

    // ให้ instanceof ทำงานถูกเมื่อ target ต่ำกว่า ES2015 (มักไม่จำเป็นถ้า target ES2022)
    Object.setPrototypeOf(this, ValidationError.prototype);
  }
}

class NotFoundError extends Error {
  constructor(public readonly resource: string, public readonly id: string) {
    super(`${resource} #${id} ไม่พบ`);
    this.name = "NotFoundError";
  }
}

super(message) ตั้ง .message; ตั้ง .name เองเสมอ (ใช้ใน log, error report)

narrow error ใน catch

async function handleRequest(id: string) {
  try {
    const user = await findUser(id);
    return processUser(user);
  } catch (error) {
    // error: unknown
    if (error instanceof ValidationError) {
      return { status: 422, body: { field: error.field, message: error.message } };
    }
    if (error instanceof NotFoundError) {
      return { status: 404, body: { message: error.message } };
    }
    if (error instanceof Error) {
      console.error("unexpected:", error.message, error.stack);
      return { status: 500, body: { message: "internal error" } };
    }
    // throw ที่ไม่ใช่ Error (throw "string" ฯลฯ)
    console.error("non-error thrown:", error);
    return { status: 500, body: { message: "internal error" } };
  }
}

ลำดับ: เจาะจงก่อน (ValidationError) → กว้าง (Error) → fallback (unknown)

error.cause — ห่อ error เดิม (ES2022)

async function loadConfig(path: string): Promise<Config> {
  try {
    const text = await readFile(path, "utf-8");
    return JSON.parse(text) as Config;
  } catch (error) {
    throw new Error(`โหลด config จาก ${path} ไม่ได้`, { cause: error });
  }
}

// caller
try {
  await loadConfig("app.json");
} catch (e) {
  if (e instanceof Error) {
    console.error(e.message);          // "โหลด config จาก app.json ไม่ได้"
    console.error("สาเหตุ:", e.cause); // error เดิม (ENOENT, SyntaxError, ...)
  }
}

discriminated union ของ error

type AppError =
  | { kind: "validation"; field: string; message: string }
  | { kind: "not_found"; resource: string }
  | { kind: "unauthorized" }
  | { kind: "network"; retryable: boolean };

function toHttpStatus(error: AppError): number {
  switch (error.kind) {
    case "validation": return 422;
    case "not_found": return 404;
    case "unauthorized": return 401;
    case "network": return error.retryable ? 503 : 502;
  }
}

Result type — error เป็นค่า ไม่ใช่ exception

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function ok<T>(value: T): Result<T, never> {
  return { ok: true, value };
}
function err<E>(error: E): Result<never, E> {
  return { ok: false, error };
}

function parseAge(input: string): Result<number, string> {
  const n = Number(input);
  if (Number.isNaN(n)) return err(`"${input}" ไม่ใช่ตัวเลข`);
  if (n < 0 || n > 150) return err(`อายุ ${n} นอกช่วง`);
  return ok(n);
}

// caller — compiler บังคับให้เช็ค .ok ก่อนเข้าถึง .value
const result = parseAge("25");
if (result.ok) {
  console.log(result.value + 1);   // number
} else {
  console.error(result.error);      // string
}

ข้อดี Result:

  • error เป็นส่วนหนึ่งของ signature — เห็นได้ว่า function อาจ fail
  • compiler บังคับจัดการ (ต่างจาก exception ที่ลืม catch ได้)
  • ไม่มี performance cost ของ stack trace

ข้อเสีย:

  • verbose (ต้อง unwrap ทุกที่)
  • ไม่ propagate อัตโนมัติ (exception bubble ขึ้นเอง)
  • ไม่ใช่ idiom หลักของ JS/TS (library ส่วนใหญ่ throw)

ใช้ Result สำหรับ error ที่ คาดหวังได้และ caller ต้องจัดการ (parse, validate); ใช้ throw สำหรับ error ที่ ผิดปกติ (bug, dependency ล่ม)

async Result

async function fetchUser(id: string): Promise<Result<User, "not_found" | "network">> {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (res.status === 404) return err("not_found");
    if (!res.ok) return err("network");
    return ok((await res.json()) as User);
  } catch {
    return err("network");
  }
}

library แนะนำ

  • neverthrow — Result type ที่มี method chain (.map, .mapErr, .andThen)
  • ts-results, @badrap/result

เรื่องที่คนมักพลาด

  • ไม่ตั้ง this.name ใน custom error — log แสดง “Error” ไม่ใช่ “ValidationError”
  • error.message ใน catch โดยไม่เช็ค instanceof Error — error เป็น unknown
  • จับ Error ก่อน ValidationError — ลำดับผิด, subclass ไม่มีวันถูกจับ
  • Result type แล้วลืม narrow — เข้าถึง .value ก่อนเช็ค .ok → error (ดี)
  • ใช้ Result ทุกที่ — exception ที่ผิดปกติจริง ๆ (out of memory, bug) throw เหมาะกว่า
  • throw ค่าที่ไม่ใช่ Error — throw "message" — เสีย stack trace; throw new Error(...) เสมอ
  • ไม่ใช้ cause — ห่อ error แล้วสูญเสียต้นตอ; new Error(msg, { cause: original })

สรุป

  • custom error: class X extends Error { constructor() { super(msg); this.name = "X"; } } + field เพิ่ม
  • narrow ใน catch (e: unknown) ด้วย e instanceof CustomError (เจาะจงก่อนกว้าง)
  • error.cause (ES2022) — ห่อ error เดิม: new Error(msg, { cause: e })
  • discriminated union ของ error ({ kind: "validation"; ... }) — exhaustive handling
  • Result type { ok: true; value } | { ok: false; error } — error เป็นค่า, compiler บังคับจัดการ; ใช้กับ error ที่คาดได้ (parse/validate)
  • exception ยังเหมาะกับ error ผิดปกติ (bug, dependency ล่ม)

บทถัดไปว่าด้วย array method และ iteration ให้ type ถูก — map/filter/reduce กับ generics, ReadonlyArray, Object.entries