JavaScript มี Error (ข้อผิดพลาด) 3 ประเภทหลัก ต่างกันที่ เวลาเกิด, สาเหตุ, และวิธีจัดการ
1. Syntax Errors (ข้อผิดพลาดไวยากรณ์ / Parsing Errors)
- เกิดขณะ Parse/Compile โค้ด (ก่อนรัน)
- โค้ดไม่ถูกต้องตาม Grammar ของภาษา
- Script หยุดทำงานทันที ไม่รันบรรทัดไหนเลย
- เฉพาะ Thread/Script ที่มี Error ถูกกระทบ (Script อื่นรันต่อได้)
// ตัวอย่าง Syntax Errors
if (x = 5) { } // Missing ) → SyntaxError
var x = ; // Missing expression
function { } // Missing name
"unclosed string; // Unclosed quote
{ } // Unexpected token (ในบาง Context)
2. Runtime Errors (ข้อผิดพลาดขณะรัน / Exceptions)
- เกิดขณะ Execution (หลัง Parse ผ่าน) เรียกว่า Exceptions
- โค้ด Syntax ถูกต้อง แต่ Logic/Environment ผิด
- กระทบเฉพาะ Thread ที่ Error (Thread อื่นทำงานต่อได้)
- จับได้ด้วย
try...catch
// ตัวอย่าง Runtime Errors
null.f(); // TypeError: Cannot read property 'f' of null
undefined(); // TypeError: undefined is not a function
JSON.parse("invalid json"); // SyntaxError (แต่เป็น Runtime!)
x(); // ReferenceError: x is not defined
eval("invalid code"); // SyntaxError (Runtime)
new Array(-1); // RangeError: Invalid array length
decodeURIComponent("%"); // URIError
3. Logical Errors (ข้อผิดพลาดตรรกะ)
- โค้ดรันไม่ Error แต่ ผลลัพธ์ผิด ตาม Business Logic
- ยากที่สุดในการ Debug เพราะไม่มี Error Message
- ไม่สามารถ Catch ด้วย try-catch ได้ (ไม่ใช่ Exception)
- ขึ้นอยู่กับ Business Requirement ว่าถูก/ผิด
// ตัวอย่าง Logical Errors
function calculateDiscount(price, discount) {
return price * discount; // ผิด! ควรเป็น price * (1 - discount) หรือ price - price*discount
}
function isAdult(age) {
return age > 18; // ผิด! ควร >= 18 (กฎหมายไทย)
}
function sum(arr) {
let total = 0;
for (let i = 1; i <= arr.length; i++) { // Off-by-one: i=1, <= length
total += arr[i]; // arr[length] = undefined
}
return total; // NaN
}
ตารางเปรียบเทียบ
| ประเภท | เวลาเกิด | จับได้ด้วย try-catch | ผลกระทบ | ตัวอย่าง |
|---|---|---|---|---|
| Syntax Error | Parse Time | ❌ ไม่ได้ (Parse Failed) | Script หยุด | Missing bracket, typo |
| Runtime Error | Execution Time | ✅ ได้ | Thread หยุด | null reference, type error |
| Logical Error | Execution Time | ❌ ไม่ได้ | ผลลัพธ์ผิด | Wrong formula, off-by-one |
เครื่องมือช่วยหา Error
- Syntax Error: IDE/Editor (Red Squiggly), ESLint, TypeScript Compiler
- Runtime Error: Browser DevTools Console, Try-Catch, Error Tracking (Sentry, LogRocket)
- Logical Error: Debugger (Breakpoints), Unit Tests, Console.log, Code Review
Error Handling Strategy
// 1. Prevent Syntax Error: Linting, TypeScript
// 2. Handle Runtime Error: Try-Catch, Global Error Handler
window.addEventListener('error', (event) => {
logError(event.error);
});
// 3. Catch Logical Error: Unit Testing
test('calculateDiscount', () => {
expect(calculateDiscount(100, 0.1)).toBe(90); // 10% off = 90
});