สามารถดึง Stack Trace ใน JavaScript ได้โดยสร้าง Error object แล้วเข้าถึง property stack
ตัวอย่าง
<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>
ผลลัพธ์ตัวอย่าง (Chrome)
Error
at stackTrace (https://example.com/test.html:5:17)
at https://example.com/test.html:8:9
at HTMLDocument.<anonymous> (https://example.com/test.html:9:13)
...
รายละเอียดเพิ่มเติม
Error.stackเป็น non-standard แต่รองรับในทุกเบราว์เซอร์สมัยใหม่- รูปแบบอาจแตกต่างกันเล็กน้อยในแต่ละ Engine (V8, SpiderMonkey, JavaScriptCore)
- ใน Production ควรใช้ Library เช่น
stacktrace.jsหรือส่งไป Error Tracking Service (Sentry, LogRocket, ฯลฯ)
กรณีใช้งานจริง
// Wrapper สำหรับ logging
function logError(fn) {
return function(...args) {
try {
return fn.apply(this, args);
} catch (e) {
console.error("Error:", e.message, "\nStack:", e.stack);
throw e; // re-throw ถ้าต้องการ
}
};
}
// ใช้งาน
const safeFunc = logError(riskyFunction);
หมายเหตุ: รูปภาพในบทความต้นฉบับแสดงตัวอย่าง Stack Trace ใน Chrome DevTools