Skip to content

Error Handling

การจัดการ errors อย่างถูกต้องทำให้ app ไม่ crash และ user ได้รับข้อความที่เป็นประโยชน์

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 {
undefinedFunction();
} catch (error) {
console.log(error.name); // "ReferenceError"
console.log(error.message); // "undefinedFunction is not defined"
console.log(error.stack); // stack trace สำหรับ debug
}
Typeสาเหตุ
ReferenceErrorใช้ตัวแปรที่ไม่ได้ประกาศ
TypeErrorใช้ method กับ type ที่ผิด เช่น null.foo
SyntaxErrorsyntax ผิดเช่น JSON ไม่ valid
RangeErrorค่าเกิน range เช่น Array(-1)
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 ได้"
}
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/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
}
}
// ใน React — Error Boundary component จับ render errors
// ใน vanilla JS — global handler
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled promise rejection:", event.reason);
// ส่ง error ไป logging service
});
window.addEventListener("error", (event) => {
console.error("Uncaught error:", event.error);
});