function getStack() {
const obj = {};
if ("captureStackTrace" in Error) {
// Avoid getStack itself in the stack trace
Error.captureStackTrace(obj, getStack);
}
return obj.stack;
}
function foo() {
console.log(getStack());
}
foo();
// Error
// at foo (<anonymous>:8:15)
// at <anonymous>:11:1Error.captureStackTrace() / notebook
Error.captureStackTrace()
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
class MyError extends Error {
constructor(message, options) {
super(message, options);
if ("captureStackTrace" in Error) {
// Avoid MyError itself in the stack trace
Error.captureStackTrace(this, MyError);
}
}
}
const myError = new MyError("Something went wrong");
console.log(myError.stack);
// Error: Something went wrong
// at <anonymous>:8:17class MyError {
constructor(message) {
this.message = message;
if ("captureStackTrace" in Error) {
// Avoid MyError itself in the stack trace
Error.captureStackTrace(this, MyError);
}
}
}
const myError = new MyError("Something went wrong");
console.log(myError.stack);
// Error: Something went wrong
// at <anonymous>:8:17