การดึง Stack Trace เมื่อ throw exception ทำได้โดยสร้าง Error object แล้วอ่าน property stack คล้ายกับการดึงปกติ แต่ทำในบล็อก catch
ตัวอย่าง
<html>
<head>
<script>
function stackTrace() {
var err = new Error();
return err.stack;
}
console.log(stackTrace());
document.write(stackTrace());
</script>
</head>
<body>
<p>Stacktrace แสดงด้านบน</p>
</body>
</html>
ผลลัพธ์ตัวอย่าง
(รูปภาพในต้นฉบับแสดง Stack Trace ใน Chrome DevTools)
รูปแบบการใช้งานจริงกับ try-catch
try {
// โค้ดที่อาจ error
riskyOperation();
} catch (e) {
// e.stack มีอยู่แล้วใน Error object
console.error("Error:", e.message);
console.error("Stack:", e.stack);
// ส่งไป Error Tracking Service
reportError({
message: e.message,
stack: e.stack,
timestamp: new Date().toISOString(),
url: window.location.href
});
}
สร้าง Custom Error พร้อม Stack
class AppError extends Error {
constructor(message, code) {
super(message);
this.name = "AppError";
this.code = code;
// Error.captureStackTrace(this, AppError); // V8 only - ตัด stack frame ของ constructor
}
}
throw new AppError("Validation failed", "VALIDATION_ERROR");
ข้อควรระวัง
- Stack Trace อาจไม่ครบถ้วนใน Production (minified code, transpiled code)
- ใช้ Source Maps เพื่อ map กลับไปโค้ดต้นฉบับ
Error.captureStackTraceใช้ได้เฉพาะ V8 (Node.js, Chrome)