or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Error Ex

Error Ex is a utility library for creating custom Error subclasses in JavaScript with enhanced stack trace customization and message formatting capabilities. It enables developers to easily create named error types with custom properties that can modify stack traces by adding contextual lines, appending information to error messages, or completely customizing the message format.

Package Information

  • Package Name: error-ex
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install error-ex

Core Imports

const errorEx = require('error-ex');

Basic Usage

const errorEx = require('error-ex');

// Create a simple custom error type
const JSONError = errorEx('JSONError');
const err = new JSONError('invalid JSON syntax');
err.name; // 'JSONError'
throw err; // JSONError: invalid JSON syntax

// Add stack line information
const FileError = errorEx('FileError', {
  fileName: errorEx.line('in %s')
});
const fileErr = new FileError('read failed');
fileErr.fileName = '/path/to/file.json';
throw fileErr; // Includes "in /path/to/file.json" in stack trace

// Append to error message
const ParseError = errorEx('ParseError', {
  fileName: errorEx.append('in %s')
});
const parseErr = new ParseError('syntax error');
parseErr.fileName = '/path/to/file.json';
throw parseErr; // ParseError: syntax error in /path/to/file.json

Architecture

Error Ex provides a simple but powerful architecture for error customization:

  • Error Constructor Factory: The main errorEx() function creates custom error constructors with enhanced capabilities
  • Property Modifiers: Custom properties can trigger message modification, stack line insertion, or direct stack manipulation
  • Helper Functions: errorEx.append() and errorEx.line() provide common property modifier patterns
  • Error Inheritance: Generated error constructors properly inherit from Error with correct prototype chains

Capabilities

Error Ex Function

Creates a new ErrorEx error type constructor with optional property-based customization.

/**
 * Create a new ErrorEx error type constructor
 * @param {string} [name] - Name of the error type (defaults to Error.name)
 * @param {Object} [properties] - Property modifiers for customizing error behavior
 * @returns {Function} Constructor function that creates custom error instances
 */
function errorEx(name, properties)

The properties parameter is an object where:

  • Keys are property names that will be looked up on error instances
  • Values are modifier objects that can contain:
    • line: Function that returns a string to add as a stack line
    • stack: Function that directly manipulates the stack array
    • message: Function that modifies the error message

Usage Examples:

// Basic named error
const CustomError = errorEx('CustomError');

// Error with stack line addition
const DetailedError = errorEx('DetailedError', {
  context: {
    line: function(value) {
      return value ? `Context: ${value}` : null;
    }
  }
});

// Error with message modification
const FormattedError = errorEx('FormattedError', {
  details: {
    message: function(value, message) {
      if (value) {
        return [`${message[0]} - Details: ${value}`];
      }
      return message;
    }
  }
});

// Error with stack manipulation
const StackError = errorEx('StackError', {
  source: {
    stack: function(value, stack) {
      if (value) {
        stack.push(`  >> Source: ${value}`);
      }
    }
  }
});

Append Helper

Creates a property modifier that appends text to error messages using string templates.

/**
 * Create a property modifier that appends text to error messages
 * @param {string} str - Template string with %s placeholder for property value
 * @param {*} [def] - Default value if property is not set
 * @returns {Object} Property modifier object with message function
 */
function errorEx.append(str, def)

Usage Examples:

// Basic append usage
const FileError = errorEx('FileError', {
  fileName: errorEx.append('in %s')
});
const err = new FileError('read failed');
err.fileName = '/path/to/file';
// Message becomes: "read failed in /path/to/file"

// With default value
const LocationError = errorEx('LocationError', {
  location: errorEx.append('at %s', 'unknown location')
});
const err = new LocationError('error occurred');
// Without setting err.location: "error occurred at unknown location"
// With err.location = 'line 42': "error occurred at line 42"

// Multiple properties
const DetailedError = errorEx('DetailedError', {
  file: errorEx.append('in %s'),
  line: errorEx.append('at line %s')
});
const err = new DetailedError('parse error');
err.file = 'script.js';
err.line = 25;
// Message becomes: "parse error in script.js at line 25"

Line Helper

Creates a property modifier that adds formatted lines to error stack traces.

/**
 * Create a property modifier that adds lines to error stack traces
 * @param {string} str - Template string with %s placeholder for property value
 * @param {*} [def] - Default value if property is not set
 * @returns {Object} Property modifier object with line function
 */
function errorEx.line(str, def)

Usage Examples:

// Basic line usage
const FileError = errorEx('FileError', {
  fileName: errorEx.line('in %s')
});
const err = new FileError('read failed');
err.fileName = '/path/to/file.json';
// Stack trace includes:
//   FileError: read failed
//       in /path/to/file.json
//       at ...

// With default value
const ContextError = errorEx('ContextError', {
  context: errorEx.line('Context: %s', 'no context available')
});
const err = new ContextError('operation failed');
// Without setting err.context: stack includes "Context: no context available"
// With err.context = 'user action': stack includes "Context: user action"

// Multiple line properties
const DetailedError = errorEx('DetailedError', {
  file: errorEx.line('File: %s'),
  operation: errorEx.line('Operation: %s'),
  user: errorEx.line('User: %s')
});
const err = new DetailedError('process failed');
err.file = 'data.json';
err.operation = 'validation';
err.user = 'alice';
// Stack trace includes multiple context lines:
//   DetailedError: process failed
//       File: data.json
//       Operation: validation
//       User: alice
//       at ...

Error Constructor API

The constructors returned by errorEx() create error instances with enhanced capabilities:

/**
 * Constructor for custom error instances (can be called with or without 'new')
 * @param {string|Error} message - Error message or existing Error to copy from
 * @returns {Error} Custom error instance with enhanced properties
 */
function ErrorConstructor(message)

Instance Properties

Custom error instances have these enhanced properties:

  • name: String - the custom error name specified in errorEx()
  • message: String - getter/setter with custom formatting based on properties
  • stack: String - getter/setter with custom stack line insertion based on properties

Advanced Usage Patterns

// Working with existing errors
const originalErr = new Error('original message');
const CustomError = errorEx('CustomError');
CustomError.call(originalErr); // Transform existing error
originalErr.name; // 'CustomError'

// Constructor can accept existing Error objects
const newErr = new CustomError(originalErr);
newErr.message; // 'original message'

// Custom property modifiers with complex logic
const SmartError = errorEx('SmartError', {
  metadata: {
    message: function(value, messageLines) {
      if (value && typeof value === 'object') {
        const meta = Object.entries(value)
          .map(([k, v]) => `${k}: ${v}`)
          .join(', ');
        return messageLines.concat([`Metadata: ${meta}`]);
      }
      return messageLines;
    },
    line: function(value) {
      if (value && value.source) {
        return `Source: ${value.source}`;
      }
      return null;
    }
  }
});

Types

/**
 * Property modifier object for customizing error behavior
 */
interface PropertyModifier {
  /** Function that returns a string to add as a stack line */
  line?: (value: any) => string | null;
  /** Function that directly manipulates the stack array */
  stack?: (value: any, stack: string[]) => void;
  /** Function that modifies the error message */
  message?: (value: any, messageLines: string[]) => string[] | string;
}

/**
 * Properties configuration object
 */
interface ErrorProperties {
  [propertyName: string]: PropertyModifier;
}

/**
 * Enhanced error constructor with custom capabilities
 */
interface ErrorConstructor {
  new (message?: string | Error): Error;
  (message?: string | Error): Error;
}