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.

JavascriptForm Validation

Code

javascriptsnippet
31 lines
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: true

Behavior 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

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.