Error Object มี Property name บอกประเภทข้อผิดพลาด มี 6 ประเภทหลัก:
| ประเภท | คำอธิบาย |
|---|---|
| EvalError | ข้อผิดพลาดใน eval() (เก่า ลดน้อย) |
| RangeError | ค่าตัวเลขเกินขอบเขต (เช่น Array length ติดลบ) |
| ReferenceError | อ้างอิงตัวแปรที่ไม่มีอยู่ (เรียกก่อนประกาศ) |
| SyntaxError | Syntax ผิดพลาด (Parser จับได้ตอน Compile) |
| TypeError | ชนิดข้อมูลไม่ตรง (เช่น เรียก method ของ null) |
| URIError | encodeURI/decodeURI ใช้ผิด |
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Error Names</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Error name values in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to call variable before declaration </h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
try {
resEle.innerHTML = a; // ReferenceError
} catch (err) {
resEle.innerHTML = "Error name = " + err.name + "<br>";
resEle.innerHTML += "Error message = " + err.message;
}
let a = 44; // Hoisting ทำให้ a เป็น undefined ที่บรรทัดบน
});
</script>
</body>
</html>
คำอธิบาย
- ตัวอย่างก่อให้เกิด ReferenceError (เข้าถึง
aก่อนlet a) err.name= "ReferenceError",err.message= "Cannot access 'a' before initialization"- Error อื่นที่พบบ่อย:
TypeError: Cannot read property of null
ผลลัพธ์
Error name = ReferenceError
Error message = Cannot access 'a' before initialization