Error Handling
Error Handling
Section titled “Error Handling”การจัดการ errors อย่างถูกต้องทำให้ app ไม่ crash และ user ได้รับข้อความที่เป็นประโยชน์
try / catch / finally
Section titled “try / catch / finally”try { // code ที่อาจ error const data = JSON.parse('{"invalid json');} catch (error) { // จัดการ error console.error("Parse error:", error.message);} finally { // ทำเสมอ ไม่ว่าจะ error หรือไม่ console.log("Cleanup done");}try: data = json.loads('{"invalid json')except json.JSONDecodeError as e: print(f"Parse error: {e}")finally: print("Cleanup done")// C ไม่มี try/catch — ใช้ return codesint result = parse_json(input, &data);if (result != 0) { fprintf(stderr, "Parse error\n");}-- T-SQL ใช้ TRY...CATCHBEGIN TRY SELECT 1/0;END TRYBEGIN CATCH SELECT ERROR_MESSAGE();END CATCHError Object
Section titled “Error Object”try { undefinedFunction();} catch (error) { console.log(error.name); // "ReferenceError" console.log(error.message); // "undefinedFunction is not defined" console.log(error.stack); // stack trace สำหรับ debug}Error Types ที่พบบ่อย
Section titled “Error Types ที่พบบ่อย”| Type | สาเหตุ |
|---|---|
ReferenceError | ใช้ตัวแปรที่ไม่ได้ประกาศ |
TypeError | ใช้ method กับ type ที่ผิด เช่น null.foo |
SyntaxError | syntax ผิดเช่น JSON ไม่ valid |
RangeError | ค่าเกิน range เช่น Array(-1) |
Throwing Errors
Section titled “Throwing Errors”function divide(a, b) { if (b === 0) { throw new Error("ไม่สามารถหารด้วย 0 ได้"); } return a / b;}
try { const result = divide(10, 0);} catch (error) { console.error(error.message); // "ไม่สามารถหารด้วย 0 ได้"}Custom Errors
Section titled “Custom Errors”class ValidationError extends Error { constructor(field, message) { super(message); this.name = "ValidationError"; this.field = field; }}
class NotFoundError extends Error { constructor(resource, id) { super(`${resource} #${id} not found`); this.name = "NotFoundError"; this.resource = resource; this.id = id; }}
// ใช้งานfunction validateAge(age) { if (typeof age !== "number") { throw new ValidationError("age", "Age must be a number"); } if (age < 0 || age > 150) { throw new ValidationError("age", "Age must be 0-150"); }}Async Error Handling
Section titled “Async Error Handling”// async/await — ใช้ try/catch ปกติasync function fetchUser(id) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) { throw new NotFoundError("User", id); } return await res.json(); } catch (error) { if (error instanceof NotFoundError) { console.warn(error.message); return null; } throw error; // re-throw unexpected errors }}Error Boundaries (Concept)
Section titled “Error Boundaries (Concept)”// ใน React — Error Boundary component จับ render errors// ใน vanilla JS — global handlerwindow.addEventListener("unhandledrejection", (event) => { console.error("Unhandled promise rejection:", event.reason); // ส่ง error ไป logging service});
window.addEventListener("error", (event) => { console.error("Uncaught error:", event.error);});