Error.captureStackTrace Hides Internal Helper Frames
Pass a helper function to V8 Error.captureStackTrace so custom validation errors trim internal helper frames and highlight the caller site first.
Code
class ValidationError extends Error {
constructor(message, boundaryFn) {
super(message);
this.name = 'ValidationError';
// Exclude boundaryFn and internal frames above it from the captured stack
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, boundaryFn ?? ValidationError);
}
}
}
function assertValidPort(port) {
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new ValidationError(`invalid port: ${port}`, assertValidPort);
}
}
function loadServerConfig(port) {
assertValidPort(port);
}
try {
loadServerConfig(70000);
} catch (err) {
const topFrames = err.stack
.split('\n')
.slice(0, 3)
.map((line) => line.trim().replace(/\s+\(.*\)$/, '').replace(/file:\/\/\/.*\//, ''));
console.log('frames:', topFrames.join(' | '));
console.log('helper hidden:', !err.stack.includes('assertValidPort'), '| caller shown:', err.stack.includes('loadServerConfig'));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
frames: V | a | l
helper hidden: true | caller shown: trueBehavior overview — Error.captureStackTrace Hides Internal Helper Frames
One way to read it: the class ValidationError and the functions assertValidPort and loadServerConfig, doing all the work.
The failure path is explicit — ValidationError is raised when the guard condition holds.
Points of care
- The import surface (if any) is all standard library, all versioned with the language itself.
Using it
The entry-point signature is function assertValidPort(port)
The demo output is labeled (frames:, helper hidden:); each label names the call that printed it.
Key statements
.map((line) => line.trim().replace(/\s+\(.*\)$/, '').replace(/file:\/\/\/.*\//, ''));
throw new ValidationError(`invalid port: ${port}`, assertValidPort);
Error.captureStackTrace(this, boundaryFn ?? ValidationError);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is there a failure path for bad input?
- The code refuses to continue: `ValidationError` is thrown while the state is still recoverable.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `assertValidPort`, `loadServerConfig` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.