สร้าง Custom Exceptions ใน JavaScript โดยใช้คำสั่ง throw ส่งค่าใดก็ได้ (String, Number, Object, Error Instance) แล้วจับด้วย catch
ตัวอย่างพื้นฐาน (Throw String)
<html>
<head>
<script>
function myFunc() {
var a = 30, b = 0;
try {
if (b == 0) {
throw "Divide by zero error."; // Throw String
} else {
var c = a / b;
}
} catch (e) {
alert("Error: " + e);
}
}
</script>
</head>
<body>
<p>คลิกเพื่อดูผลลัพธ์:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
แนะนำ: Throw Error Object (หรือ Subclass)
// 1. Throw Error Instance
throw new Error("Divide by zero");
// 2. Custom Error Class (ES6 Class)
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
// Error.captureStackTrace(this, ValidationError); // V8 only
}
}
throw new ValidationError("Email is required", "email");
// 3. ใช้งาน
try {
validateForm({ email: "" });
} catch (e) {
if (e instanceof ValidationError) {
console.log("Field:", e.field); // "email"
}
console.error(e.message);
}
ประเภท Error Built-in ที่ Extend ได้
Error- พื้นฐานTypeError- ชนิดข้อมูลผิดRangeError- ค่าออกนอกช่วงReferenceError- ตัวแปรไม่มีอยู่SyntaxError- ไวยากรณ์ผิด (ไม่จับได้ด้วย try-catch)URIError- URI ผิดEvalError- eval ผิด (Legacy)
Best Practices
- Throw
Errorobjects (มี stack trace) ไม่ใช่ String/Primitive - สร้าง Custom Error Classes สำหรับ Domain Errors
- ใส่ข้อมูลเพิ่มเติมใน Error (code, field, statusCode, ฯลฯ)
- ใช้
instanceofตรวจสอบประเภทใน catch block - Re-throw หากไม่สามารถจัดการได้:
throw e;