npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

certus-adivalt

v1.0.3

Published

Certain Adi Vault - The most reliable error handling, response management, and logging system

Readme

CertusAdiValt

The Certain Shield for Your Applications

Where Certainty Meets Elegance in Modern Application Development

npm version License: MIT TypeScript Bundle Size Downloads Build Status PRs Welcome

Introduction

CertusAdiValt is a comprehensive TypeScript library designed to provide robust, type-safe utilities for modern application development. It offers a complete suite of tools for error handling, logging, configuration management, and API response standardization, helping developers build reliable and maintainable applications with confidence.

Key Features

  • 🛡️ Comprehensive Error Handling - Hierarchical error system with type-safe error classes
  • 📝 Structured Logging - Multiple formatters with sensitive data redaction
  • ⚙️ Configuration Management - Environment-aware configuration with validation
  • 🔄 Standardized Responses - Consistent API response formatting
  • 🔧 Utility Functions - Common development utilities and helpers
  • 🛠️ Express Middleware - Ready-to-use middleware for web applications
  • 📦 TypeScript First - Full TypeScript support with extensive type definitions

Installation

npm install certus-adivalt

Quick Start

import { 
  ConfigManager, 
  ValtLogger, 
  CertusResponseBuilder,
  CorrelationMiddleware,
  ErrorMiddleware,
  LogLevel 
} from 'certus-adivalt';

// Initialize configuration
const configManager = ConfigManager.getInstance();
configManager.initialize({
  logger: {
    level: LogLevel.INFO,
    service: 'my-app',
    environment: 'development'
  }
});

// Create logger instance
const logger = new ValtLogger(configManager.getLoggerConfig());

// Use in your application
logger.info('Application started successfully');

// Create standardized API responses
const successResponse = CertusResponseBuilder.success(
  { id: 1, name: 'Example' },
  'Data retrieved successfully'
);

Architecture Overview

CertusAdiValt follows a modular architecture with clear separation of concerns:

certus-adivalt/
├── adi/          # Configuration and utilities
├── certus/       # Error handling system
├── responses/    # API response management
├── valt/         # Logging and middleware
├── types/        # Type definitions
└── constants/    # Constants and messages

Module Dependencies

  • ADI Module: Foundation layer for configuration and utilities
  • Certus Module: Depends on ADI for configuration
  • Responses Module: Depends on Certus for error handling
  • Valt Module: Depends on all other modules for comprehensive functionality

Table of Contents

Types

Core Configuration Types

| Name | Description | Value/Structure | |------|-------------|-----------------| | Environment | Runtime environment of the application | 'development' \| 'stagging' \| 'production' \| 'test' | | LogLevel | Logging severity levels | ERROR = 0, WARN = 1, INFO = 2, DEBUG = 3, TRACE = 4 | | BaseContext | Base context shared across logger, errors, responses | { timestamp: Date; requestId?: string; userId?: string; sessionId?: string; [key: string]: unknown; } | | PaginationParams | Pagination details for paginated responses | { page: number; limit: number; total: number; totalPages: number; hasNext: boolean; hasPrev: boolean; } | | CertusAdiValtConfig | Main configuration object | Complex object with errors, logger, responses, and middleware sections |

Error Handling Types

| Name | Description | Value/Structure | |------|-------------|-----------------| | ErrorContext | Additional metadata for errors | Extends BaseContext with error-specific fields like code, statusCode, details, etc. | | CertusErrorOptions | Options for creating CertusError instances | { code: string; statusCode: number; context?: Record<string, unknown>; originalError?: Error; includeStack?: boolean; } |

Logging Types

| Name | Description | Value/Structure | |------|-------------|-----------------| | LogEntry | Represents a single log entry | Extends BaseContext with log-specific fields like level, message, service, error, etc. | | LoggerConfig | Logger configuration for initialization | { level: LogLevel; service: string; environment: string; version?: string; redactFields?: string[]; prettyPrint?: boolean; timestampFormat?: string; } |

Response Types

| Name | Description | Value/Structure | |------|-------------|-----------------| | SuccessResponse<T> | Success response wrapper for API results | { success: true; data: T; message?: string; timestamp: string; requestId?: string; meta?: Record<string, unknown>; } | | ErrorResponse | Standard structure for error API responses | { success: false; error: { code: string; message: string; details?: string; statusCode: number; timestamp: string; context?: Record<string, unknown>; requestId?: string; }; } | | PaginatedResponse<T> | Paginated list response | { success: true; data: T[]; pagination: PaginationParams; timestamp: string; requestId?: string; meta?: Record<string, unknown>; } | | EmptyResponse | Response for operations with no data return | { success: true; message?: string; timestamp: string; requestId?: string; } | | ApiResponse<T> | Union of all possible API response shapes | SuccessResponse<T> \| ErrorResponse \| PaginatedResponse<T> \| EmptyResponse |

Constants

Error Codes

| Category | Name | Description | Value | |----------|------|-------------|-------| | Authentication | AUTH_INVALID_CREDENTIALS | Invalid username, password, or credentials | 'AUTH_INVALID_CREDENTIALS' | | | AUTH_TOKEN_EXPIRED | Authentication token has expired | 'AUTH_TOKEN_EXPIRED' | | | AUTH_INSUFFICIENT_PERMISSIONS | User lacks required permissions | 'AUTH_INSUFFICIENT_PERMISSIONS' | | Validation | VAL_INVALID_INPUT | General input validation failure | 'VAL_INVALID_INPUT' | | | VAL_REQUIRED_FIELD | Required field is missing or empty | 'VAL_REQUIRED_FIELD' | | | VAL_INVALID_EMAIL | Email address format is invalid | 'VAL_INVALID_EMAIL' | | Database | DB_CONNECTION_ERROR | Cannot establish connection to database | 'DB_CONNECTION_ERROR' | | | DB_RECORD_NOT_FOUND | Requested record not found in database | 'DB_RECORD_NOT_FOUND' | | | DB_UNIQUE_CONSTRAINT | Database unique constraint violation | 'DB_UNIQUE_CONSTRAINT' | | File & Storage | FILE_UPLOAD_ERROR | File upload operation failed | 'FILE_UPLOAD_ERROR' | | | FILE_NOT_FOUND | Requested file not found in storage | 'FILE_NOT_FOUND' | | | FILE_TOO_LARGE | File size exceeds allowed limit | 'FILE_TOO_LARGE' | | Server | SRV_INTERNAL_ERROR | Generic internal server error | 'SRV_INTERNAL_ERROR' | | | SRV_EXTERNAL_SERVICE | External service or API call failed | 'SRV_EXTERNAL_SERVICE' | | | SRV_RATE_LIMIT | Rate limit exceeded for server operation | 'SRV_RATE_LIMIT' | | Generic | GEN_NOT_FOUND | Generic resource not found error | 'GEN_NOT_FOUND' | | | GEN_BAD_REQUEST | Generic bad request error | 'GEN_BAD_REQUEST' | | | GEN_UNKNOWN_ERROR | Unknown or unclassified error | 'GEN_UNKNOWN_ERROR' |

HTTP Status Codes

| Category | Name | Description | Value | |----------|------|-------------|-------| | Success (2xx) | OK | The request has succeeded | 200 | | | CREATED | New resource created successfully | 201 | | | NO_CONTENT | Success but no content to return | 204 | | Client Errors (4xx) | BAD_REQUEST | Server cannot process due to client error | 400 | | | UNAUTHORIZED | Authentication credentials missing/invalid | 401 | | | FORBIDDEN | Server understood but refuses to authorize | 403 | | | NOT_FOUND | Requested resource not found | 404 | | | TOO_MANY_REQUESTS | Rate limiting applied | 429 | | Server Errors (5xx) | INTERNAL_SERVER_ERROR | Unexpected server condition | 500 | | | SERVICE_UNAVAILABLE | Server temporarily unable to handle request | 503 | | | GATEWAY_TIMEOUT | Upstream server didn't respond in time | 504 |

User Messages

Error Messages

| Category | Name | User-Friendly Message | |----------|------|----------------------| | Authentication | AUTH_INVALID_CREDENTIALS | "Invalid email or password" | | | AUTH_TOKEN_EXPIRED | "Authentication token has expired" | | | AUTH_INSUFFICIENT_PERMISSIONS | "Insufficient permissions to access this resource" | | Validation | VAL_INVALID_INPUT | "Invalid input provided" | | | VAL_REQUIRED_FIELD | "This field is required" | | | VAL_INVALID_EMAIL | "Invalid email address" | | Database | DB_CONNECTION_ERROR | "Database connection failed" | | | DB_RECORD_NOT_FOUND | "Record not found" | | File | FILE_UPLOAD_ERROR | "File upload failed" | | | FILE_TOO_LARGE | "File size exceeds limit" |

Success Messages

| Name | Message | |------|---------| | OPERATION_SUCCESSFUL | "Operation completed successfully" | | LOGIN_SUCCESSFUL | "Login successful" | | REGISTRATION_SUCCESSFUL | "Registration successful" | | FILE_UPLOADED | "File uploaded successfully" | | DATA_CREATED | "Data created successfully" |

Informational Messages

| Name | Message | |------|---------| | ACCOUNT_PENDING_VERIFICATION | "Please verify your account to continue" | | PASSWORD_RESET_EMAIL_SENT | "Password reset instructions sent to your email" | | MAINTENANCE_SCHEDULED | "Scheduled maintenance in progress" |

Type Aliases

| Name | Description | Value | |------|-------------|-------| | ErrorCodeType | Union of all possible error codes | (typeof ErrorCodes)[keyof typeof ErrorCodes] | | HttpStatusType | Union of all possible HTTP status codes | (typeof HttpStatus)[keyof typeof HttpStatus] | | ErrorMessageType | Union of all possible error messages | (typeof ErrorMessages)[keyof typeof ErrorMessages] | | SuccessMessageType | Union of all possible success messages | (typeof SuccessMessages)[keyof typeof SuccessMessages] | | InfoMessageType | Union of all possible informational messages | (typeof InfoMessages)[keyof typeof InfoMessages] |

Usage Examples

Type Usage

import { Environment, LogLevel, BaseContext } from 'certus-adi-valt';

const env: Environment = 'development';
const level: LogLevel = LogLevel.INFO;
const context: BaseContext = {
  timestamp: new Date(),
  requestId: 'req-123',
  userId: 'user-456'
};

Constant Usage

import { ErrorCodes, HttpStatus, ErrorMessages } from 'certus-adi-valt';

// Error handling
if (authFailed) {
  throw new Error(ErrorMessages[ErrorCodes.AUTH_INVALID_CREDENTIALS]);
}

// HTTP responses
return response.status(HttpStatus.CREATED).json({
  success: true,
  message: 'User created successfully'
});

Adi

ConfigManager Class

Class Overview

Description: Singleton configuration manager for the CertusAdiValt system. Responsible for loading, validating, and providing access to the application configuration with environment-specific defaults.

Pattern: Implements singleton pattern to ensure consistent configuration access.

Static Methods

getInstance()

Description: Gets the singleton instance of ConfigManager. Creates a new instance if one doesn't exist, otherwise returns the existing instance.

Returns: ConfigManager - The singleton ConfigManager instance

Example:

const configManager = ConfigManager.getInstance();

Instance Methods

initialize(userConfig?)

Description: Initializes the configuration manager with optional user overrides. Merges user configuration with defaults and validates the result.

Parameters:

  • userConfig: Partial<CertusAdiValtConfig> (optional) - Partial configuration object containing user-specific overrides

Throws:

  • CertusAdiValtError - CFG_ALREADY_INITIALIZED when configuration already initialized
  • CertusAdiValtError - Various validation errors for invalid configuration

Example:

configManager.initialize({
  logger: {
    level: LogLevel.DEBUG,
    service: 'my-app'
  }
});

getConfig()

Description: Gets the complete configuration object. Returns a deep copy to prevent external modification.

Returns: CertusAdiValtConfig - Complete configuration object

Throws:

  • CertusAdiValtError - CFG_NOT_INITIALIZED when configuration not initialized

Example:

const config = configManager.getConfig();
console.log(config.logger.level);

getErrorsConfig()

Description: Gets the errors configuration section.

Returns: Object - Errors configuration containing settings for includeStack, logErrors, exposeDetails, formatError

Example:

const errorsConfig = configManager.getErrorsConfig();

getLoggerConfig()

Description: Gets the logger configuration section.

Returns: Object - Logger configuration containing settings for level, service, environment, redactFields, prettyPrint, timestampFormat, version

Example:

const loggerConfig = configManager.getLoggerConfig();

getResponsesConfig()

Description: Gets the responses configuration section.

Returns: Object - Responses configuration containing settings for includeTimestamp, includeRequestId, successMessage, pagination

Example:

const responsesConfig = configManager.getResponsesConfig();

getMiddlewareConfig()

Description: Gets the middleware configuration section.

Returns: Object - Middleware configuration containing settings for enableErrorHandler, enableLogging, enableSecurity, skipPaths

Example:

const middlewareConfig = configManager.getMiddlewareConfig();

isDevelopment()

Description: Checks if the current environment is development.

Returns: boolean - True if environment is 'development', false otherwise

Example:

if (configManager.isDevelopment()) {
  // Enable development-only features
}

isProduction()

Description: Checks if the current environment is production.

Returns: boolean - True if environment is 'production', false otherwise

Example:

if (configManager.isProduction()) {
  // Enable production optimizations
}

isStaging()

Description: Checks if the current environment is staging.

Returns: boolean - True if environment is 'stagging', false otherwise

Example:

if (configManager.isStaging()) {
  // Use staging-specific settings
}

isTest()

Description: Checks if the current environment is test.

Returns: boolean - True if environment is 'test', false otherwise

Example:

if (configManager.isTest()) {
  // Use test database
}

updateConfig(updates)

Description: Updates the configuration with partial changes. Performs deep merge and revalidates.

Parameters:

  • updates: Partial<CertusAdiValtConfig> - Partial configuration object containing settings to update

Throws:

  • CertusAdiValtError - CFG_NOT_INITIALIZED when configuration not initialized
  • CertusAdiValtError - Various validation errors for invalid configuration

Example:

configManager.updateConfig({
  logger: { level: LogLevel.ERROR }
});

getEnvVar(key, defaultValue?)

Description: Gets a required environment variable.

Parameters:

  • key: string - Environment variable name
  • defaultValue: string (optional) - Default value if environment variable not set

Returns: string - Environment variable value

Throws:

  • CertusAdiValtError - CFG_MISSING_ENV_VAR when environment variable not set and no default provided

Example:

const dbUrl = configManager.getEnvVar('DATABASE_URL');
const port = configManager.getEnvVar('PORT', '3000');

getEnvVarOptional(key, defaultValue?)

Description: Gets an optional environment variable.

Parameters:

  • key: string - Environment variable name
  • defaultValue: string (optional) - Default value if environment variable not set

Returns: string | undefined - Environment variable value, default value, or undefined

Example:

const apiKey = configManager.getEnvVarOptional('API_KEY');
const timeout = configManager.getEnvVarOptional('TIMEOUT', '5000');

getEnvVarNumber(key, defaultValue?)

Description: Gets a required numeric environment variable.

Parameters:

  • key: string - Environment variable name
  • defaultValue: number (optional) - Default number if environment variable not set

Returns: number - Parsed numeric value

Throws:

  • CertusAdiValtError - CFG_MISSING_ENV_VAR when environment variable not set and no default provided
  • CertusAdiValtError - CFG_INVALID_ENV_VAR when value cannot be parsed as number

Example:

const port = configManager.getEnvVarNumber('PORT', 3000);
const workers = configManager.getEnvVarNumber('WORKER_COUNT');

getEnvVarBoolean(key, defaultValue?)

Description: Gets a required boolean environment variable.

Parameters:

  • key: string - Environment variable name
  • defaultValue: boolean (optional) - Default boolean if environment variable not set

Returns: boolean - Parsed boolean value

Throws:

  • CertusAdiValtError - CFG_MISSING_ENV_VAR when environment variable not set and no default provided
  • CertusAdiValtError - CFG_INVALID_ENV_VAR when value cannot be parsed as boolean

Example:

const debug = configManager.getEnvVarBoolean('DEBUG', false);
const ssl = configManager.getEnvVarBoolean('SSL_ENABLED', true);

reset()

Description: Resets the configuration to defaults and marks as uninitialized. Primarily for testing.

Example:

configManager.reset();

CommonUtils Class

Class Overview

Description: A collection of common utility functions used throughout the CertusAdiValt system. Provides helper methods for cloning, validation, string manipulation, and async operations.

Pattern: All methods are static and can be used without instantiating the class.

Static Methods

deepClone(obj)

Description: Deep clone an object, handling dates, arrays, and nested objects.

Parameters:

  • obj: T - The object to deep clone

Returns: T - A deep clone of the original object

Example:

const original = { a: 1, b: { c: 2 } };
const cloned = CommonUtils.deepClone(original);

isEmpty(value)

Description: Check if a value is empty. Handles null, undefined, empty strings, arrays, and objects.

Parameters:

  • value: any - The value to check for emptiness

Returns: boolean - True if value is considered empty, false otherwise

Example:

CommonUtils.isEmpty(null); // true
CommonUtils.isEmpty('hello'); // false
CommonUtils.isEmpty([]); // true
CommonUtils.isEmpty([1, 2]); // false

generateRandomString(length?)

Description: Generate a cryptographically insecure random string of specified length.

Parameters:

  • length: number (optional) - Length of random string (default: 16)

Returns: string - Random string of specified length

Throws:

  • Error - If length is not a positive integer

Example:

const random = CommonUtils.generateRandomString(32);

sleep(ms)

Description: Sleep for specified milliseconds. Returns a promise that resolves after the delay.

Parameters:

  • ms: number - Number of milliseconds to sleep

Returns: Promise<void> - Promise that resolves after specified milliseconds

Example:

await CommonUtils.sleep(1000);
console.log('1 second later');

retry(fn, options?)

Description: Retry an async function with exponential backoff and configurable retry logic.

Parameters:

  • fn: () => Promise<T> - Async function to retry
  • options: Object (optional) - Retry configuration
    • maxAttempts: number (default: 3) - Maximum retry attempts
    • delayMs: number (default: 1000) - Initial delay between attempts
    • backoffMultiplier: number (default: 2) - Multiplier for delay after each attempt
    • shouldRetry: (error: Error) => boolean (default: () => true) - Function to determine if error should be retried

Returns: Promise<T> - Promise resolving with result of successful function call

Throws:

  • CertusAdiValtError - UTL_RETRY_EXHAUSTED when all retry attempts exhausted
  • Error - The original error if shouldRetry returns false

Example:

const result = await CommonUtils.retry(
  () => apiCall(),
  { maxAttempts: 5, delayMs: 500 }
);

debounce(func, wait, immediate?)

Description: Debounce function execution. Delays function execution until after wait milliseconds have elapsed since last invocation.

Parameters:

  • func: T - The function to debounce
  • wait: number - Number of milliseconds to delay
  • immediate: boolean (optional) - If true, trigger function on leading edge (default: false)

Returns: (...args: Parameters<T>) => void - Debounced function

Example:

const debouncedSearch = CommonUtils.debounce(
  (query: string) => performSearch(query), 
  300
);

throttle(func, limit)

Description: Throttle function execution. Ensures function is only called at most once per specified limit.

Parameters:

  • func: T - The function to throttle
  • limit: number - Number of milliseconds between allowed executions

Returns: (...args: Parameters<T>) => void - Throttled function

Example:

const throttledScroll = CommonUtils.throttle(
  () => updateScrollPosition(), 
  100
);

safeJsonParse(jsonString, defaultValue?)

Description: Parse JSON safely with default value fallback.

Parameters:

  • jsonString: string - JSON string to parse
  • defaultValue: T (optional) - Default value if parsing fails

Returns: T | undefined - Parsed JSON object or defaultValue if parsing fails

Example:

const obj = CommonUtils.safeJsonParse('{"a": 1}');
const fallback = CommonUtils.safeJsonParse('invalid', { fallback: true });

safeJsonStringify(obj, defaultValue?)

Description: Stringify JSON safely with error handling and default value fallback.

Parameters:

  • obj: any - Object to stringify
  • defaultValue: string (optional) - Default JSON string if stringification fails (default: '{}')

Returns: string - JSON string representation of the object

Example:

const json = CommonUtils.safeJsonStringify({ a: 1 });
const fallback = CommonUtils.safeJsonStringify(circularObj, '{"error": true}');

isValidEmail(email)

Description: Validate email format using basic regex pattern.

Parameters:

  • email: string - Email address to validate

Returns: boolean - True if email format is valid, false otherwise

Example:

CommonUtils.isValidEmail('[email protected]'); // true
CommonUtils.isValidEmail('invalid-email'); // false

isValidUrl(url)

Description: Validate URL format using the URL constructor.

Parameters:

  • url: string - URL string to validate

Returns: boolean - True if URL format is valid, false otherwise

Example:

CommonUtils.isValidUrl('https://example.com'); // true
CommonUtils.isValidUrl('not-a-url'); // false

formatBytes(bytes, decimals?)

Description: Format bytes to human readable string with appropriate unit.

Parameters:

  • bytes: number - Number of bytes to format
  • decimals: number (optional) - Number of decimal places (default: 2)

Returns: string - Formatted string with appropriate unit

Throws:

  • Error - If bytes is negative

Example:

CommonUtils.formatBytes(1048576); // "1 MB"
CommonUtils.formatBytes(1234567, 0); // "1 MB"

generateId(prefix?)

Description: Generate a unique ID combining timestamp and random characters.

Parameters:

  • prefix: string (optional) - Optional prefix for generated ID (default: '')

Returns: string - Unique ID string

Example:

CommonUtils.generateId(); // "kf91pzabc123"
CommonUtils.generateId('user_'); // "user_kf91pzabc123"

maskSensitiveData(str, visibleChars?)

Description: Mask sensitive data in strings, showing only specified number of characters at ends.

Parameters:

  • str: string - String containing sensitive data to mask
  • visibleChars: number (optional) - Number of characters to keep visible at start and end (default: 4)

Returns: string - Masked string with middle characters replaced by asterisks

Example:

CommonUtils.maskSensitiveData('1234567890123456'); // "1234************3456"
CommonUtils.maskSensitiveData('secret-token', 2); // "se********en"

isNodeEnvironment()

Description: Check if code is running in a Node.js environment.

Returns: boolean - True if running in Node.js, false otherwise

Example:

if (CommonUtils.isNodeEnvironment()) {
  // Use Node.js specific APIs
}

isBrowserEnvironment()

Description: Check if code is running in a browser environment.

Returns: boolean - True if running in browser, false otherwise

Example:

if (CommonUtils.isBrowserEnvironment()) {
  // Use browser specific APIs
}

Usage Examples

Configuration Management

// Initialize configuration
const configManager = ConfigManager.getInstance();
configManager.initialize({
  logger: {
    level: LogLevel.DEBUG,
    service: 'my-service'
  }
});

// Use configuration
if (configManager.isDevelopment()) {
  console.log('Running in development mode');
}

// Update configuration dynamically
configManager.updateConfig({
  logger: { level: LogLevel.INFO }
});

Common Utilities

// Deep cloning
const original = { data: { nested: 'value' } };
const cloned = CommonUtils.deepClone(original);

// Retry with exponential backoff
const result = await CommonUtils.retry(
  () => fetchDataFromAPI(),
  { maxAttempts: 3, delayMs: 1000 }
);

// Debounce user input
const debouncedSearch = CommonUtils.debounce(
  (query) => searchAPI(query),
  300
);

// Safe JSON operations
const data = CommonUtils.safeJsonParse(jsonString, {});
const json = CommonUtils.safeJsonStringify(data);

Certus

Base Error Classes

CertusAdiValtError Class

Description: Custom error class for the CertusAdiValt system with enhanced error handling capabilities. Extends native Error class to include structured error information, HTTP status codes, contextual metadata, and chainable builder methods.

Constructor

Parameters:

  • message: string - Human-readable error description
  • code: string (optional) - Machine-readable error code (default: ErrorCodes.SRV_INTERNAL_ERROR)
  • statusCode: number (optional) - HTTP status code (default: HttpStatus.INTERNAL_SERVER_ERROR)
  • context: Record<string, unknown> (optional) - Additional error context (default: {})
  • originalError: Error (optional) - Original error that caused this error

Example:

throw new CertusAdiValtError('User not found', 'USER_NOT_FOUND', 404);

Methods

toJSON()

Description: Converts the error to a structured JSON representation suitable for API responses.

Returns: ErrorContext - Structured error context object with all error details

Example:

const error = new CertusAdiValtError('Not found', 'NOT_FOUND', 404);
const json = error.toJSON();
toLog()

Description: Converts the error to a log-friendly format with reduced verbosity.

Returns: Record<string, unknown> - Simplified error representation for logging

Example:

const error = new CertusAdiValtError('DB error', 'DB_ERROR', 500);
const logData = error.toLog();
console.error('Operation failed:', logData);
withContext(context)

Description: Creates a new error instance with additional context merged into existing context.

Parameters:

  • context: Record<string, unknown> - Additional context to merge

Returns: this - New error instance with merged context

Example:

const error = new CertusAdiValtError('Error')
  .withContext({ userId: 123 })
  .withContext({ operation: 'create' });
withCode(code)

Description: Creates a new error instance with the specified error code.

Parameters:

  • code: string - New error code to use

Returns: this - New error instance with updated code

Example:

const error = new CertusAdiValtError('Error').withCode('VALIDATION_ERROR');
withStatusCode(statusCode)

Description: Creates a new error instance with the specified HTTP status code.

Parameters:

  • statusCode: number - New HTTP status code to use

Returns: this - New error instance with updated status code

Example:

const error = new CertusAdiValtError('Error').withStatusCode(400);
withMessage(message)

Description: Creates a new error instance with the specified error message.

Parameters:

  • message: string - New error message to use

Returns: this - New error instance with updated message

Example:

const error = new CertusAdiValtError('Initial').withMessage('More specific error message');

Client Error Classes (4xx)

CertusClientError Class

Description: Base client error class for all client-side (4xx) errors. Represents errors that are the client's responsibility.

Constructor Parameters:

  • message: string - Human-readable error description
  • code: string (optional) - Machine-readable error code (default: ErrorCodes.GEN_VALIDATION_ERROR)
  • statusCode: number (optional) - HTTP status code (default: HttpStatus.BAD_REQUEST)
  • context: Record<string, unknown> (optional) - Additional context about the client error

Example:

throw new CertusClientError('Invalid request parameters', 'CUSTOM_CLIENT_ERROR', 400);

CertusValidationError Class

Description: Error thrown when input data fails validation rules. Returns HTTP 422 Unprocessable Entity.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Validation failed')
  • context: Record<string, unknown> (optional) - Additional context about validation failures

Example:

throw new CertusValidationError('User data validation failed', { errors: validation.errors });

CertusNotFoundError Class

Description: Error thrown when a requested resource cannot be found. Returns HTTP 404 Not Found.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Resource not found')
  • context: Record<string, unknown> (optional) - Additional context about the missing resource

Example:

throw new CertusNotFoundError(`User with ID ${userId} not found`, { resource: 'User', id: userId });

CertusUnauthorizedError Class

Description: Error thrown when authentication is required but not provided or invalid. Returns HTTP 401 Unauthorized.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Unauthorized access')
  • context: Record<string, unknown> (optional) - Additional context about the authorization failure

Example:

throw new CertusUnauthorizedError('Authentication required to access this resource');

CertusForbiddenError Class

Description: Error thrown when the client is authenticated but lacks permission for the requested action. Returns HTTP 403 Forbidden.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Access forbidden')
  • context: Record<string, unknown> (optional) - Additional context about the permission denial

Example:

throw new CertusForbiddenError('Only administrators can delete users', { userRole: user.role });

Authentication Error Classes

CertusAuthenticationError Class

Description: Base authentication error class for all authentication-related failures.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Authentication failed')
  • code: string (optional) - Machine-readable error code (default: ErrorCodes.AUTH_INVALID_CREDENTIALS)
  • statusCode: number (optional) - HTTP status code (default: HttpStatus.UNAUTHORIZED)
  • context: Record<string, unknown> (optional) - Additional authentication context

Example:

throw new CertusAuthenticationError('Multi-factor authentication required', ErrorCodes.AUTH_MFA_REQUIRED);

CertusInvalidCredentialsError Class

Description: Error thrown when user credentials (username/password) are invalid or incorrect.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Invalid credentials')
  • context: Record<string, unknown> (optional) - Additional context about the credential failure

Example:

throw new CertusInvalidCredentialsError('Username or password is incorrect', { username, attemptCount: 3 });

CertusTokenExpiredError Class

Description: Error thrown when an authentication token (JWT, access token, etc.) has expired.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Token has expired')
  • context: Record<string, unknown> (optional) - Additional context about the token expiration

Example:

throw new CertusTokenExpiredError('Your session has expired. Please log in again.', { tokenId: token.id });

CertusInsufficientPermissionsError Class

Description: Error thrown when a user lacks sufficient permissions to perform an action. Returns HTTP 403 Forbidden.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Insufficient permissions')
  • context: Record<string, unknown> (optional) - Additional context about the permission failure

Example:

throw new CertusInsufficientPermissionsError('You do not have permission to delete users', { requiredPermission: 'delete_users' });

CertusSessionRevokedError Class

Description: Error thrown when a user's session has been explicitly revoked or invalidated.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Session has been revoked')
  • context: Record<string, unknown> (optional) - Additional context about the session revocation

Example:

throw new CertusSessionRevokedError('This session was terminated by the user', { sessionId, revokedAt: session.revokedAt });

Server Error Classes (5xx)

CertusServerError Class

Description: Base server error class for all server-side (5xx) errors. Represents errors that are the server's responsibility.

Constructor Parameters:

  • message: string - Human-readable error description
  • code: string (optional) - Machine-readable error code (default: ErrorCodes.SRV_INTERNAL_ERROR)
  • statusCode: number (optional) - HTTP status code (default: HttpStatus.INTERNAL_SERVER_ERROR)
  • context: Record<string, unknown> (optional) - Additional context about the server error

Example:

throw new CertusServerError('Failed to process payment workflow', ErrorCodes.SRV_PROCESSING_ERROR, 500);

CertusInternalServerError Class

Description: Error thrown for generic internal server errors when no more specific error applies. Returns HTTP 500 Internal Server Error.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Internal server error')
  • context: Record<string, unknown> (optional) - Additional context about the internal error

Example:

throw new CertusInternalServerError('An unexpected error occurred', { operation: 'business_critical_operation' });

CertusExternalServiceError Class

Description: Error thrown when external service dependencies fail or return errors. Returns HTTP 502 Bad Gateway.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'External service error')
  • context: Record<string, unknown> (optional) - Additional context about the external service failure

Example:

throw new CertusExternalServiceError('Payment gateway unavailable', { service: 'stripe_payment_gateway', operation: 'charge' });

CertusConfigurationError Class

Description: Error thrown when application configuration is invalid, missing, or misconfigured. Returns HTTP 500 Internal Server Error.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Configuration error')
  • context: Record<string, unknown> (optional) - Additional context about the configuration issue

Example:

throw new CertusConfigurationError('Database connection string is required', { missingVariable: 'DATABASE_URL' });

Database Error Classes

CertusDatabaseError Class

Description: Base database error class for all database-related failures.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Database error occurred')
  • code: string (optional) - Machine-readable error code (default: ErrorCodes.DB_QUERY_ERROR)
  • statusCode: number (optional) - HTTP status code (default: HttpStatus.INTERNAL_SERVER_ERROR)
  • context: Record<string, unknown> (optional) - Additional context about the database error

Example:

throw new CertusDatabaseError('Failed to create user record', ErrorCodes.DB_QUERY_ERROR, 500, { table: 'users' });

CertusUniqueConstraintError Class

Description: Error thrown when a database unique constraint violation occurs. Returns HTTP 409 Conflict.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Unique constraint violation')
  • context: Record<string, unknown> (optional) - Additional context about the constraint violation

Example:

throw new CertusUniqueConstraintError('Email address already registered', { field: 'email', value: '[email protected]' });

CertusConnectionError Class

Description: Error thrown when database connection issues occur. Returns HTTP 503 Service Unavailable.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Database connection error')
  • context: Record<string, unknown> (optional) - Additional context about the connection failure

Example:

throw new CertusConnectionError('Unable to connect to database', { host: config.database.host, port: config.database.port });

CertusTimeoutError Class

Description: Error thrown when database operations exceed their time limits. Returns HTTP 504 Gateway Timeout.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Database operation timed out')
  • context: Record<string, unknown> (optional) - Additional context about the timeout

Example:

throw new CertusTimeoutError('Database query exceeded time limit', { query: 'complex_aggregation', timeoutMs: 5000 });

Validation Error Classes

CertusInputValidationError Class

Description: Error thrown when input data fails basic validation rules. Returns HTTP 400 Bad Request.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Input validation failed')
  • context: Record<string, unknown> (optional) - Additional context about validation failures

Example:

throw new CertusInputValidationError('Email and password are required', { missingFields: ['email', 'password'] });

CertusSchemaValidationError Class

Description: Error thrown when data fails schema validation against a defined schema. Returns HTTP 422 Unprocessable Entity.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Schema validation failed')
  • context: Record<string, unknown> (optional) - Additional context about schema validation failures

Example:

throw new CertusSchemaValidationError('Data does not match expected schema', { schema: 'user-registration', errors: validation.errors });

CertusBusinessRuleError Class

Description: Error thrown when business rules or domain logic constraints are violated. Returns HTTP 409 Conflict.

Constructor Parameters:

  • message: string (optional) - Human-readable error description (default: 'Business rule violation')
  • context: Record<string, unknown> (optional) - Additional context about business rule violations

Example:

throw new CertusBusinessRuleError('Insufficient funds for withdrawal', { accountBalance, withdrawalAmount, deficit: withdrawalAmount - accountBalance });

Type Guard Functions

isCertusError(error)

Description: Type guard to check if an unknown value is a CertusAdiValtError instance.

Parameters:

  • error: unknown - The value to check

Returns: error is CertusAdiValtError - True if the value is a CertusAdiValtError instance

Example:

try {
  await someOperation();
} catch (error) {
  if (isCertusError(error)) {
    console.log(error.code); // Safe access to CertusAdiValtError properties
  }
}

isClientError(error)

Description: Checks if an error is a client error (4xx status code range).

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with 4xx status code

Example:

if (isClientError(error)) {
  showUserErrorMessage(error.message);
} else {
  showGenericErrorMessage();
}

isServerError(error)

Description: Checks if an error is a server error (5xx status code range).

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with 5xx status code

Example:

if (isServerError(error)) {
  sendAlertToOpsTeam(error);
  return createServerErrorResponse();
}

isAuthenticationError(error)

Description: Checks if an error is an authentication-related error.

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with AUTH_ prefix error code

Example:

if (isAuthenticationError(error)) {
  clearUserSession();
  return redirectToLogin();
}

isValidationError(error)

Description: Checks if an error is a validation-related error.

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with VAL_ prefix error code

Example:

if (isValidationError(error)) {
  const fieldErrors = extractValidationErrors(error);
  highlightInvalidFields(fieldErrors);
}

isDatabaseError(error)

Description: Checks if an error is a database-related error.

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with DB_ prefix error code

Example:

if (isDatabaseError(error)) {
  if (error.code === 'DB_CONNECTION_ERROR') {
    await reconnectToDatabase();
    return retryOperation();
  }
}

isExternalServiceError(error)

Description: Checks if an error is specifically an external service error.

Parameters:

  • error: unknown - The error to check

Returns: boolean - True if the error is a CertusAdiValtError with SRV_EXTERNAL_SERVICE error code

Example:

if (isExternalServiceError(error)) {
  monitoring.logExternalServiceFailure('payment_gateway', error);
}

Factory Functions

createCertusError(message, options)

Description: Creates a generic CertusAdiValtError with full customization options.

Parameters:

  • message: string - Human-readable error description
  • options: CertusErrorOptions - Error configuration options

Returns: CertusAdiValtError - New CertusAdiValtError instance

Example:

const error = createCertusError('Inventory allocation failed', {
  code: 'INVENTORY_ALLOCATION_FAILED',
  statusCode: 409,
  context: { productId: 'prod_123', requestedQty: 10, availableQty: 5 }
});

createValidationError(message, context)

Description: Creates a validation error for input or data validation failures.

Parameters:

  • message: string (optional) - Human-readable error description (default: 'Validation failed')
  • context: Record<string, unknown> (optional) - Additional context about validation failures

Returns: CertusValidationError - New CertusValidationError instance

Example:

throw createValidationError('Email format is invalid');

createNotFoundError(message, context)

Description: Creates a not found error for missing resources or entities.

Parameters:

  • message: string (optional) - Human-readable error description (default: 'Resource not found')
  • context: Record<string, unknown> (optional) - Additional context about the missing resource

Returns: CertusNotFoundError - New CertusNotFoundError instance

Example:

throw createNotFoundError('User not found');

createAuthenticationError(message, context)

Description: Creates an authentication error for credential or token failures.

Parameters:

  • message: string (optional) - Human-readable error description (default: 'Authentication failed')
  • context: Record<string, unknown> (optional) - Additional context about authentication failure

Returns: CertusAuthenticationError - New CertusAuthenticationError instance

Example:

throw createAuthenticationError('Invalid credentials');

Utility Functions

wrapError(error, message, code)

Description: Wraps an unknown error into a CertusAdiValtError, preserving original error information.

Parameters:

  • error: unknown - The error to wrap (can be any type)
  • message: string (optional) - Optional custom error message (uses original message if not provided)
  • code: string (optional) - Error code for the wrapped error (default: ErrorCodes.SRV_INTERNAL_ERROR)

Returns: CertusAdiValtError - CertusAdiValtError instance (original if already a Certus error)

Example:

try {
  JSON.parse(invalidJson);
} catch (error) {
  throw wrapError(error, 'Failed to parse JSON data');
}

toClientError(error)

Description: Converts an unknown error to a client error (4xx status code).

Parameters:

  • error: unknown - The error to convert

Returns: CertusClientError - CertusClientError instance

Example:

const clientError = toClientError(error);
return res.status(clientError.statusCode).json(clientError.toJSON());

toServerError(error)

Description: Converts an unknown error to a server error (5xx status code).

Parameters:

  • error: unknown - The error to convert

Returns: CertusServerError - CertusServerError instance

Example:

const serverError = toServerError(error);
logger.error('Background job failed:', serverError.toLog());

Assertion Functions

assertCertusError(error, message)

Description: Asserts that an unknown value is a CertusAdiValtError instance.

Parameters:

  • error: unknown - The value to assert as CertusAdiValtError
  • message: string (optional) - Custom error message for assertion failure

Throws: CertusServerError - Throws if the value is not a CertusAdiValtError

Example:

function processError(error: unknown) {
  assertCertusError(error, 'Expected a Certus error for processing');
  console.log(error.code); // Safe access
}

assertClientError(error, message)

Description: Asserts that an unknown value is a client error (4xx status code).

Parameters:

  • error: unknown - The value to assert as CertusClientError
  • message: string (optional) - Custom error message for assertion failure

Throws: CertusServerError - Throws if the value is not a CertusClientError

Example:

function formatClientErrorResponse(error: unknown) {
  assertClientError(error, 'Expected client error for response formatting');
  return {
    status: error.statusCode,
    code: error.code,
    message: error.message
  };
}

Usage Examples

Basic Error Creation

// Simple error
throw new CertusAdiValtError('User not found', 'USER_NOT_FOUND', 404);

// With builder pattern
throw new CertusAdiValtError('Initial error')
  .withCode('VALIDATION_ERROR')
  .withStatusCode(400)
  .withContext({ field: 'email', value: 'invalid' });

Error Handling

try {
  await someOperation();
} catch (error) {
  if (isCertusError(error)) {
    // Handle known Certus errors
    if (isClientError(error)) {
      logger.warn('Client error:', error.toLog());
    } else if (isServerError(error)) {
      logger.error('Server error:', error.toLog());
      sendAlertToOpsTeam(error);
    }
  } else {
    // Wrap unknown errors
    throw wrapError(error, 'Unexpected error occurred');
  }
}

API Error Responses

app.use((error, req, res, next) => {
  if (isCertusError(error)) {
    return res.status(error.statusCode).json({
      success: false,
      error: error.toJSON()
    });
  }
  
  // Convert unknown errors to server errors
  const serverError = toServerError(error);
  return res.status(serverError.statusCode).json({
    success: false,
    error: serverError.toJSON()
  });
});

Responses

CertusAdiValt - Response System Documentation

Overview

Comprehensive response handling system with builders, formatters, and type guards for creating and handling standardized API responses in the CertusAdiValt system.

Response Builder

CertusResponseBuilder Class

Description: Response builder utility for creating standardized API responses in the CertusAdiValt system. Provides factory methods for creating consistent, well-structured API responses following the CertusAdiValt response format standards.

Static Methods

generateTimestamp()

Description: Generates an ISO 8601 timestamp for response standardization.

Returns: string - ISO 8601 formatted timestamp

Example:

const timestamp = CertusResponseBuilder.generateTimestamp();
// Returns: "2024-01-15T10:30:00.000Z"
success(data, message?, requestId?, meta?)

Description: Creates a standard success response with data payload.

Type Parameters:

  • T - Type of the data payload

Parameters:

  • data: T - The main response data payload
  • message: string (optional) - Optional success message
  • requestId: string (optional) - Optional request ID for tracing
  • meta: Record<string, unknown> (optional) - Optional additional metadata

Returns: SuccessResponse<T> - Standardized success response

Example:

// Basic success response
return CertusResponseBuilder.success({ id: 1, name: 'John' });

// Success response with message and metadata
return CertusResponseBuilder.success(
  userData,
  'User profile retrieved',
  'req_123456',
  { cache: { hit: true, ttl: 300 } }
);
error(error, requestId?)

Description: Creates a standardized error response from any error object.

Parameters:

  • error: CertusAdiValtError | Error - The error to convert to response format
  • requestId: string (optional) - Optional request ID for tracing

Returns: ErrorResponse - Standardized error response

Example:

// From CertusAdiValtError
try {
  await authenticateUser(credentials);
} catch (error) {
  if (error instanceof CertusAdiValtError) {
    return CertusResponseBuilder.error(error, requestId);
  }
  return CertusResponseBuilder.error(error, requestId);
}

// From generic Error
try {
  JSON.parse(invalidJson);
} catch (error) {
  return CertusResponseBuilder.error(error, 'req_123456');
}
paginated(data, pagination, requestId?, meta?)

Description: Creates a paginated response for list endpoints with pagination metadata.

Type Parameters:

  • T - Type of items in the data array

Parameters:

  • data: T[] - Array of paginated items
  • pagination: PaginationParams - Pagination metadata
  • requestId: string (optional) - Optional request ID for tracing
  • meta: Record<string, unknown> (optional) - Optional additional metadata

Returns: PaginatedResponse<T> - Standardized paginated response

Example:

const pagination = {
  page: 1,
  limit: 20,
  total: 150,
  totalPages: 8,
  hasNext: true,
  hasPrev: false
};
return CertusResponseBuilder.paginated(users, pagination, requestId);
empty(message?, requestId?)

Description: Creates an empty success response for operations that don't return data.

Parameters:

  • message: string (optional) - Optional success message
  • requestId: string (optional) - Optional request ID for tracing

Returns: EmptyResponse - Standardized empty success response

Example:

// Basic empty response
return CertusResponseBuilder.empty();

// Empty response with custom message
return CertusResponseBuilder.empty('Operation completed successfully', 'req_123456');

// For DELETE endpoints
await userRepository.delete(userId);
return CertusResponseBuilder.empty('User deleted successfully', requestId);
created(data, message?, requestId?)

Description: Creates a success response specifically for resource creation (HTTP 201 equivalent).

Type Parameters:

  • T - Type of the created resource data

Parameters:

  • data: T - The created resource data
  • message: string (optional) - Success message (default: 'Resource created successfully')
  • requestId: string (optional) - Optional request ID for tracing

Returns: SuccessResponse<T> - Standardized creation success response

Example:

// Create user response
const newUser = await userRepository.create(userData);
return CertusResponseBuilder.created(newUser, 'User created successfully', requestId);

// Create with custom message
return CertusResponseBuilder.created(
  product,
  'Product added to catalog',
  requestId
);
updated(data, message?, requestId?)

Description: Creates a success response specifically for resource updates (HTTP 200/204 equivalent).

Type Parameters:

  • T - Type of the updated resource data

Parameters:

  • data: T - The updated resource data
  • message: string (optional) - Success message (default: 'Resource updated successfully')
  • requestId: string (optional) - Optional request ID for tracing

Returns: SuccessResponse<T> - Standardized update success response

Example:

// Update user response
const updatedUser = await userRepository.update(userId, updateData);
return CertusResponseBuilder.updated(updatedUser, 'User profile updated', requestId);

// Partial update response
return CertusResponseBuilder.updated(
  partialUser,
  'User preferences updated',
  requestId
);
deleted(message?, requestId?)

Description: Creates an empty success response specifically for resource deletion.

Parameters:

  • message: string (optional) - Success message (default: 'Resource deleted successfully')
  • requestId: string (optional) - Optional request ID for tracing

Returns: EmptyResponse - Standardized deletion success response

Example:

// Delete user response
await userRepository.delete(userId);
return CertusResponseBuilder.deleted('User account deleted', requestId);

// Delete with custom message
return CertusResponseBuilder.deleted(
  'Product removed from inventory',
  requestId
);

Response Formatter

ResponseFormatter Class

Description: High-level response formatting utility for the CertusAdiValt system. Provides simplified, opinionated methods for formatting API responses with sensible defaults and enhanced error handling.

Static Methods

formatSuccess(data, options?)

Description: Formats a successful API response with data payload.

Type Parameters:

  • T - Type of the data payload

Parameters:

  • data: T - The main response data payload
  • options: Object (optional) - Response formatting options
    • message: string (optional) - Optional success message
    • requestId: string (optional) - Optional request ID for tracing
    • meta: Record<string, unknown> (optional) - Optional additional metadata

Returns: ApiResponse<T> - Formatted success response

Example:

// Basic success response
return ResponseFormatter.formatSuccess({ id: 1, name: 'John' });

// Success with all options
return ResponseFormatter.formatSuccess(
  userData,
  {
    message: 'User profile retrieved successfully',
    requestId: 'req_123456',
    meta: {
      cache: { hit: true, ttl: 300 },
      permissions: ['read', 'write']
    }
  }
);
formatError(error, options?)

Description: Formats an error response from any type of error with enhanced handling.

Parameters:

  • error: unknown - The error to format (any type)
  • options: Object (optional) - Error formatting options
    • requestId: string (optional) - Optional request ID for tracing
    • includeDetails: boolean (optional) - Whether to include detailed error messages in production (default: false)

Returns: ApiResponse - Formatted error response

Example:

// Handle CertusAdiValtError (preserves original structure)
try {
  await userService.authenticate(credentials);
} catch (error) {
  return ResponseFormatter.formatError(error, {
    requestId: req.requestId
  });
}

// Handle generic errors with detail masking
try {
  JSON.parse(invalidJson);
} catch (error) {
  return ResponseFormatter.formatError(error, {
    requestId: req.requestId,
    includeDetails: process.env.NODE_ENV === 'development' // Show details only in dev
  });
}
formatPaginated(data, pagination, options?)

Description: Formats a paginated response with automatic pagination metadata calculation.

Type Parameters:

  • T - Type of items in the data array

Parameters:

  • data: T[] - Array of paginated items
  • pagination: Object - Basic pagination parameters
    • page: number - Current page number (1-based)
    • limit: number - Number of items per page
    • total: number - Total number of items across all pages
  • options: Object (optional) - Pagination formatting options
    • requestId: string (optional) - Optional request ID for tracing
    • meta: Record<string, unknown> (optional) - Optional additional metadata

Returns: ApiResponse<T> - Formatted paginated response

Example:

// Basic pagination
return ResponseFormatter.formatPaginated(
  users,
  {
    page: 1,
    limit: 20,
    total: 150
  },
  {
    requestId: req.requestId
  }
);

// Pagination with metadata
return ResponseFormatter.formatPaginated(
  products,
  {
    page: 2,
    limit: 25,
    total: 1000
  },
  {
    requestId: req.requestId,
    meta: {
      filters: { category: 'electronics', priceRange: '100-500' },
      sort: { by: 'name', order: 'asc' }
    }
  }
);

Type Guard Functions

isSuccessResponse(response)

Description: Type guard to check if an API response is a success response with data.

Type Parameters:

  • T - The expected type of the data payload

Parameters:

  • response: ApiResponse<T> - The API response to check

Returns: response is SuccessResponse<T> - True if the response is a success response with data

Example:

// Type-