### setupConfig(options) Source: https://context7.com/darshan1005/intellerror/llms.txt Overrides the default IntellError configuration. Accepts a partial `IntellErrorConfig` object. Settings can also be controlled via environment variables (which are read at startup). ```APIDOC ## `setupConfig(options)` — Global Configuration ### Description Overrides the default IntellError configuration. Accepts a partial `IntellErrorConfig` object. Settings can also be controlled via environment variables (which are read at startup). ### Parameters - **options** (object) - Optional - An object containing configuration options. - **showNodeModules** (boolean) - Optional - Collapse node_modules frames (default: false). - **showNodeInternals** (boolean) - Optional - Collapse Node.js internal frames (default: false). - **suggestionsEnabled** (boolean) - Optional - Show 💡 Suggestions section (default: true). - **sourceMapsEnabled** (boolean) - Optional - Auto-resolve .map files to original source (default: true). - **interceptWarnings** (boolean) - Optional - Enhance console.warn() output (default: false). - **showSearchLinks** (boolean) - Optional - Show Google/SO/GitHub links (default: true). - **useJsonMode** (boolean) - Optional - Use JSON output in register mode (default: false). - **webhookUrl** (string) - Optional - Slack/Discord webhook URL. ### Example Usage ```typescript import { setupConfig } from 'intellerror'; // Configure once at application startup, before any errors occur setupConfig({ showNodeModules: false, showNodeInternals: false, suggestionsEnabled: true, sourceMapsEnabled: true, interceptWarnings: true, showSearchLinks: true, useJsonMode: false, webhookUrl: 'https://hooks.slack.com/services/T00/B00/XXX' }); ``` ### Environment Variables Equivalent configuration can be set via environment variables: ``` INTELLERROR_SHOW_MODULES=false INTELLERROR_SHOW_INTERNALS=false INTELLERROR_SUGGESTIONS=true INTELLERROR_SOURCE_MAPS=true INTELLERROR_SEARCH_LINKS=true INTELLERROR_JSON=false ``` ``` -------------------------------- ### Configure Intellerror Global Settings Source: https://context7.com/darshan1005/intellerror/llms.txt Call `setupConfig` once at application startup to override default Intellerror configurations. Settings can also be managed via environment variables. ```typescript import { setupConfig } from 'intellerror'; // Configure once at application startup, before any errors occur setupConfig({ showNodeModules: false, // Collapse node_modules frames (default: false) showNodeInternals: false, // Collapse Node.js internal frames (default: false) suggestionsEnabled: true, // Show 💡 Suggestions section (default: true) sourceMapsEnabled: true, // Auto-resolve .map files to original source (default: true) interceptWarnings: true, // Enhance console.warn() output (default: false) showSearchLinks: true, // Show Google/SO/GitHub links (default: true) useJsonMode: false, // Use JSON output in register mode (default: false) webhookUrl: 'https://hooks.slack.com/services/T00/B00/XXX' // Slack/Discord webhook }); // Equivalent environment variable configuration (no code changes): // INTELLERROR_SHOW_MODULES=false // INTELLERROR_SHOW_INTERNALS=false // INTELLERROR_SUGGESTIONS=true // INTELLERROR_SOURCE_MAPS=true // INTELLERROR_SEARCH_LINKS=true // INTELLERROR_JSON=false ``` -------------------------------- ### Register IntellError for Node.js/Bun/Deno Source: https://github.com/darshan1005/intellerror/blob/main/README.md Use the --import flag with Node.js or ensure the import is present for Bun and Deno to automatically catch unhandled errors. ```bash # Node.js 20+ node --import intellerror/register index.js # Bun bun index.ts # (Auto-detected if you import it) ``` -------------------------------- ### Zero-Config Global Registration Source: https://context7.com/darshan1005/intellerror/llms.txt Automatically registers global error listeners for uncaught exceptions and unhandled rejections in Node.js, Bun, Deno, and browser environments. This allows IntellError to catch and format all unhandled errors without requiring manual try/catch blocks. ```APIDOC ## `import 'intellerror/register'` — Zero-Config Global Registration Registers global `uncaughtException`, `unhandledRejection` (Node/Bun/Edge) and `error`, `unhandledrejection` (Browser/Deno) listeners automatically. All unhandled errors are formatted and printed without any manual try/catch required. ### Usage ```typescript // Node.js 20+ — add as CLI flag, no code changes needed // node --import intellerror/register index.js // OR import at the very top of your entry file import 'intellerror/register'; // From this point on, ALL unhandled errors are caught and pretty-printed. async function riskyOperation() { const data: any = null; return data.value; // TypeError: Cannot read properties of null } // No try/catch needed — IntellError catches it globally riskyOperation(); ``` ### Example Console Output ``` ✅ IntellError Node.js listener active. ERROR TypeError: Cannot read properties of null (reading 'value') 2024-01-15T10:23:45.123Z | uptime: 0.1s | ID: a1b2c3d4 📍 Location: src/index.ts:5:14 ← YOUR CODE 💡 Suggestions: • Accessing property on a null object. You're trying to read a property from a variable that is null. Fix: Check why the object is null before accessing its properties, or use 'obj?.prop'. ``` ``` -------------------------------- ### formatWarningBrowser(message, error?) Source: https://context7.com/darshan1005/intellerror/llms.txt Formats a warning message for the browser console with yellow CSS badge styling. Returns a spread-ready array for `console.log`. ```APIDOC ## `formatWarningBrowser(message, error?)` — Browser Console Warning Formatter ### Description Formats a warning message for the browser console with yellow CSS badge styling. Returns a spread-ready array for `console.log`. ### Parameters - **message** (string) - Required - The warning message to format. - **error** (Error) - Optional - An Error object to include richer stack context. ### Example Usage ```typescript import { formatWarningBrowser } from 'intellerror'; function useDeprecatedAPI(featureName: string) { console.log(...formatWarningBrowser( `"${featureName}" is deprecated and will be removed in v2.0. Use the new API instead.` )); } useDeprecatedAPI('getUserSync'); ``` ### Output Example (Browser Console) ``` WARNING "getUserSync" is deprecated and will be removed in v2.0. Use the new API instead. 📍 Location: src/hooks/useData.ts:8:3 (YOUR CODE) ``` ``` -------------------------------- ### Configure IntellError Settings Source: https://github.com/darshan1005/intellerror/blob/main/README.md Customize IntellError's output and behavior by setting various configuration options. This allows fine-tuning for project-specific needs. ```typescript import { setupConfig } from 'intellerror'; setupConfig({ showNodeModules: false, // Hide noise? showNodeInternals: false, // Hide node internals? suggestionsEnabled: true, // Show the "💡 Suggestions"? sourceMapsEnabled: true, // Enable original source mapping? webhookUrl: 'https://...' // Push to Slack/Discord? }); ``` -------------------------------- ### registerRule(rule) Source: https://context7.com/darshan1005/intellerror/llms.txt Adds a custom context-aware suggestion rule to the engine. Rules receive the full `Error` object and parsed stack frames, and return a boolean to decide if they match. Matched rules are sorted by `confidence` (0–1) descending. ```APIDOC ## `registerRule(rule)` — Custom Suggestion Rules Adds a custom context-aware suggestion rule to the engine. Rules receive the full `Error` object and parsed stack frames, and return a boolean to decide if they match. Matched rules are sorted by `confidence` (0–1) descending. ### Parameters #### Request Body - **rule** (object) - Required - An object containing the rule definition. - **match** (function) - Required - A function that takes `err` and `stack` and returns a boolean. - **message** (string) - Required - The short error message. - **confidence** (number) - Required - A value between 0 and 1 indicating the rule's confidence. - **description** (string) - Optional - A detailed description of the error. - **fix** (string) - Optional - Suggested steps to fix the error. ### Example Usage ```typescript import { registerRule } from 'intellerror'; registerRule({ match: (err) => err.constructor.name === 'PrismaClientKnownRequestError' && err.message.includes('P2025'), message: "Prisma record not found.", confidence: 1, description: "The query returned no results for the given filter.", fix: "Use 'findFirst' instead of 'findUniqueOrThrow', or check the ID exists before querying." }); ``` ``` -------------------------------- ### Zero-Config Global Error Registration Source: https://context7.com/darshan1005/intellerror/llms.txt Automatically registers global error listeners for uncaught exceptions and unhandled rejections. Import this at the top of your entry file for automatic error handling without manual try/catch blocks. ```typescript // Node.js 20+ — add as CLI flag, no code changes needed // node --import intellerror/register index.js // OR import at the very top of your entry file import 'intellerror/register'; // From this point on, ALL unhandled errors are caught and pretty-printed. async function riskyOperation() { const data: any = null; return data.value; // TypeError: Cannot read properties of null } // No try/catch needed — IntellError catches it globally riskyOperation(); // Console output: // ✅ IntellError Node.js listener active. // // ERROR TypeError: Cannot read properties of null (reading 'value') // 2024-01-15T10:23:45.123Z | uptime: 0.1s | ID: a1b2c3d4 // // 📍 Location: // src/index.ts:5:14 ← YOUR CODE // // 💡 Suggestions: // • Accessing property on a null object. // You're trying to read a property from a variable that is null. // Fix: Check why the object is null before accessing its properties, or use 'obj?.prop'. ``` -------------------------------- ### Format Error to JSON Source: https://github.com/darshan1005/intellerror/blob/main/README.md Use this function to enable production logging that integrates seamlessly with observability platforms like Datadog, Splunk, or Loki. ```typescript import { formatErrorJSON } from 'intellerror'; try { // your code } catch (err) { console.log(formatErrorJSON(err)); } ``` -------------------------------- ### formatWarning(message, error?) Source: https://context7.com/darshan1005/intellerror/llms.txt Formats a warning message into a styled terminal string with a yellow `WARNING` badge, source location, and any matching suggestions. Optionally accepts an `Error` object for richer stack context. ```APIDOC ## `formatWarning(message, error?)` — Terminal Warning Formatter ### Description Formats a warning message into a styled terminal string with a yellow `WARNING` badge, source location, and any matching suggestions. Optionally accepts an `Error` object for richer stack context. ### Parameters - **message** (string) - Required - The warning message to format. - **error** (Error) - Optional - An Error object to include richer stack context. ### Example Usage ```typescript import { formatWarning } from 'intellerror'; function loadConfig(path: string) { if (!path.endsWith('.json')) { console.warn(formatWarning(`Config file "${path}" is not a JSON file. This may cause parse errors.`)); } // ... load config } loadConfig('config.yaml'); ``` ### Output Example ``` WARNING Config file "config.yaml" is not a JSON file. This may cause parse errors. 📍 Location: src/config-loader.ts:3:17 ← YOUR CODE ``` ``` -------------------------------- ### Register Custom Suggestion Rules with Intellerror Source: https://context7.com/darshan1005/intellerror/llms.txt Add context-aware suggestion rules to the Intellerror engine. Rules receive the full Error object and parsed stack frames, returning a boolean to indicate a match. Matched rules are sorted by confidence. ```typescript import { registerRule } from 'intellerror'; // Rule 1: Detect Prisma "record not found" errors registerRule({ match: (err) => err.constructor.name === 'PrismaClientKnownRequestError' && err.message.includes('P2025'), message: "Prisma record not found.", confidence: 1, description: "The query returned no results for the given filter.", fix: "Use 'findFirst' instead of 'findUniqueOrThrow', or check the ID exists before querying." }); // Rule 2: Context-aware rule using stack frames registerRule({ match: (err, stack) => err.message.includes('JWT') && stack.some(f => f.file?.includes('middleware/auth')), message: "JWT validation failed in auth middleware.", confidence: 0.95, description: "The token may be expired, malformed, or signed with the wrong secret.", fix: "Verify JWT_SECRET matches, check token expiry with jwt.decode(), and confirm 'Authorization: Bearer ' header format." }); // Now these rules fire automatically in formatError() and formatErrorJSON() try { await prisma.user.findUniqueOrThrow({ where: { id: 'nonexistent' } }); } catch (err) { console.log(formatError(err)); // 💡 Suggestions: // • Prisma record not found. // The query returned no results for the given filter. // Fix: Use 'findFirst' instead of 'findUniqueOrThrow' ... } ``` -------------------------------- ### Format Browser Console Warnings with Intellerror Source: https://context7.com/darshan1005/intellerror/llms.txt Use `formatWarningBrowser` to format warnings for the browser console with yellow CSS badge styling. The returned array needs to be spread (`...`) for `console.log`. ```typescript import { formatWarningBrowser } from 'intellerror'; function useDeprecatedAPI(featureName: string) { console.log(...formatWarningBrowser( `"${featureName}" is deprecated and will be removed in v2.0. Use the new API instead.` )); } useDeprecatedAPI('getUserSync'); ``` -------------------------------- ### formatErrorBrowser(error) Source: https://context7.com/darshan1005/intellerror/llms.txt Formats an error for the browser DevTools console using `%c` CSS styling directives. Must be spread with the `...` operator when passed to `console.log`. ```APIDOC ## `formatErrorBrowser(error)` — Browser Console Error Formatter ### Description Formats an error for the browser DevTools console using `%c` CSS styling directives. Must be spread with the `...` operator when passed to `console.log`. ### Parameters - **error** (Error) - Required - The error object to format. ### Example Usage ```typescript import { formatErrorBrowser } from 'intellerror'; // React Error Boundary example class ErrorBoundary extends React.Component { componentDidCatch(error: Error, info: React.ErrorInfo) { // Spread is required for CSS styles to apply correctly console.log(...formatErrorBrowser(error)); } render() { return this.props.children; } } // Manual try/catch in browser code async function loadUserProfile(id: string) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to load profile`); return await res.json(); } catch (err) { console.log(...formatErrorBrowser(err)); } } ``` ### Output Example (Browser Console) ``` TypeError Cannot read properties of undefined 📍 Location: src/components/Profile.tsx:24:10 (YOUR CODE) 💡 Suggestions: • Accessing property on undefined object. Fix: Use optional chaining like 'obj?.prop' or ensure the object is initialized. ``` ``` -------------------------------- ### Register IntellError for Browser Source: https://github.com/darshan1005/intellerror/blob/main/README.md Add this import at the top of your entry file for automatic unhandled error catching in browser environments like React, Vite, and Next.js. ```typescript import 'intellerror/register'; ``` -------------------------------- ### errorFormatter() Source: https://context7.com/darshan1005/intellerror/llms.txt An Express 4/5 error-handling middleware factory. Logs the formatted error to the server console and sends a sanitized `{ error: { name, message } }` JSON response to the client (stack traces are never leaked to clients). ```APIDOC ## `errorFormatter()` — Express Error Middleware An Express 4/5 error-handling middleware factory. Logs the formatted error to the server console and sends a sanitized `{ error: { name, message } }` JSON response to the client (stack traces are never leaked to clients). ### Usage ```typescript import express from 'express'; import { errorFormatter, setupConfig } from 'intellerror'; const app = express(); setupConfig({ webhookUrl: process.env.SLACK_WEBHOOK_URL }); // ... your routes ... // Must be registered AFTER all routes, with exactly 4 parameters app.use(errorFormatter()); app.listen(3000); ``` ### Response #### Success Response (200) - **error** (object) - Contains error details. - **name** (string) - The name of the error. - **message** (string) - The error message. #### Error Response (500) - **error** (object) - Contains error details. - **name** (string) - The name of the error. - **message** (string) - The error message. ``` -------------------------------- ### Format Terminal Warnings with Intellerror Source: https://context7.com/darshan1005/intellerror/llms.txt Use `formatWarning` to style warning messages for the terminal, including a 'WARNING' badge and source location. It can optionally include an Error object for richer context. ```typescript import { formatWarning } from 'intellerror'; function loadConfig(path: string) { if (!path.endsWith('.json')) { console.warn(formatWarning(`Config file "${path}" is not a JSON file. This may cause parse errors.`)); } // ... load config } loadConfig('config.yaml'); ``` -------------------------------- ### formatErrorJSON(error) Source: https://context7.com/darshan1005/intellerror/llms.txt Serializes a full error report into a structured JSON string, suitable for ingestion into observability tools. Includes timestamp, uptime, severity, fingerprint, parsed stack frames, error cause chain, suggestions, and source location. ```APIDOC ## `formatErrorJSON(error)` — Machine-Readable JSON Formatter Serializes a full error report to a structured JSON string, suitable for ingestion into observability tools like Datadog, Splunk, or Loki. Includes timestamp, uptime, severity, fingerprint, parsed stack frames, error cause chain, suggestions, and source location. ### Parameters - **error** (Error) - Required - The error object to format. ### Usage ```typescript import { formatErrorJSON } from 'intellerror'; class DatabaseError extends Error { severity = 'FATAL'; constructor(message: string, cause?: Error) { super(message, { cause }); this.name = 'DatabaseError'; } } try { const cause = new Error('ECONNREFUSED 127.0.0.1:5432'); throw new DatabaseError('Query execution failed', cause); } catch (err) { const json = formatErrorJSON(err); console.log(json); // Pipe to your log aggregator: // await fetch('https://logs.example.com/ingest', { method: 'POST', body: json }); } ``` ### Example JSON Output ```json { "timestamp": "2024-01-15T10:23:45.123Z", "uptime": 3.14, "severity": "FATAL", "fingerprint": "a1b2c3d4", "error": { "type": "DatabaseError", "message": "Query execution failed", "stack": [ { "file": "src/db.ts", "lineNumber": 12, "column": 9, ... } ], "causes": [ { "type": "Error", "message": "ECONNREFUSED 127.0.0.1:5432" } ] }, "suggestions": [ { "message": "Network connection refused.", "confidence": 1, "fix": "..." } ], "location": { "file": "src/db.ts", "line": 12, "column": 9, "isMapped": false } } ``` ``` -------------------------------- ### Express Error Formatting Middleware Source: https://github.com/darshan1005/intellerror/blob/main/README.md Integrate IntellError into an Express application by using the provided error formatting middleware. This automatically formats errors for Express routes. ```typescript import express from 'express'; import { errorFormatter } from 'intellerror'; const app = express(); app.use(errorFormatter()); ``` -------------------------------- ### formatError(error) Source: https://context7.com/darshan1005/intellerror/llms.txt Formats any `Error` instance into a colorized, human-readable string for Node.js terminal output. This includes severity, timestamp, uptime, fingerprint ID, source location, inline code snapshot, suggestions, and error cause chain. ```APIDOC ## `formatError(error)` — Terminal Error Formatter Formats any `Error` instance into a colorized, human-readable string for Node.js terminal output. Includes severity label, timestamp, uptime, fingerprint ID, source location, inline code snapshot, suggestions, troubleshooting links, error cause chain, and filtered stack trace. ### Parameters - **error** (Error) - Required - The error object to format. ### Usage ```typescript import { formatError } from 'intellerror'; async function fetchUserFromDB(userId: string) { throw new Error('Connection refused (timeout after 5000ms)'); } async function getUser(userId: string) { try { await fetchUserFromDB(userId); } catch (cause) { throw new Error(`Failed to load user: ${userId}`, { cause }); } } try { await getUser('user_42'); } catch (err) { console.log(formatError(err)); } ``` ### Example Terminal Output (colorized) ``` ERROR Error: Failed to load user: user_42 2024-01-15T10:23:45.123Z | uptime: 2.3s | ID: f3a9b1c2 📍 Location: src/users/service.ts:9:11 ← YOUR CODE > 9 | throw new Error(`Failed to load user: ${userId}`, { cause }); 8 | try { 10 | } 🔗 Causes: caused by: Error: Connection refused (timeout after 5000ms) 📦 Stack: → src/users/service.ts:9:11 (4 node internals hidden) ``` ``` -------------------------------- ### Format Browser Console Errors with Intellerror Source: https://context7.com/darshan1005/intellerror/llms.txt Utilize `formatErrorBrowser` to format errors for browser DevTools using CSS styling. This function must be spread (`...`) when passed to `console.log` for styles to apply. ```typescript import { formatErrorBrowser } from 'intellerror'; // React Error Boundary example class ErrorBoundary extends React.Component { componentDidCatch(error: Error, info: React.ErrorInfo) { // Spread is required for CSS styles to apply correctly console.log(...formatErrorBrowser(error)); } render() { return this.props.children; } } // Manual try/catch in browser code async function loadUserProfile(id: string) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to load profile`); return await res.json(); } catch (err) { console.log(...formatErrorBrowser(err)); } } ``` -------------------------------- ### Format Error to Machine-Readable JSON Source: https://context7.com/darshan1005/intellerror/llms.txt Serializes a full error report into a structured JSON string, suitable for ingestion into observability tools. Includes timestamp, uptime, severity, fingerprint, stack frames, and error causes. ```typescript import { formatErrorJSON } from 'intellerror'; class DatabaseError extends Error { severity = 'FATAL'; constructor(message: string, cause?: Error) { super(message, { cause }); this.name = 'DatabaseError'; } } try { const cause = new Error('ECONNREFUSED 127.0.0.1:5432'); throw new DatabaseError('Query execution failed', cause); } catch (err) { const json = formatErrorJSON(err); console.log(json); // Pipe to your log aggregator: // await fetch('https://logs.example.com/ingest', { method: 'POST', body: json }); } // Output (formatted JSON): // { // "timestamp": "2024-01-15T10:23:45.123Z", // "uptime": 3.14, // "severity": "FATAL", // "fingerprint": "a1b2c3d4", // "error": { // "type": "DatabaseError", // "message": "Query execution failed", // "stack": [ { "file": "src/db.ts", "lineNumber": 12, "column": 9, ... } ], // "causes": [ { "type": "Error", "message": "ECONNREFUSED 127.0.0.1:5432" } ] // }, // "suggestions": [ // { "message": "Network connection refused.", "confidence": 1, "fix": "..." } // ], // "location": { "file": "src/db.ts", "line": 12, "column": 9, "isMapped": false } // } ``` -------------------------------- ### Format Error for Terminal/Node.js Source: https://github.com/darshan1005/intellerror/blob/main/README.md Manually format an error object for display in the terminal or Node.js console. This provides a clean, human-readable stack trace. ```typescript import { formatError } from 'intellerror'; try { // your code... } catch (err) { console.log(formatError(err)); } ``` -------------------------------- ### Express Error-Handling Middleware with Intellerror Source: https://context7.com/darshan1005/intellerror/llms.txt Use `errorFormatter` as an Express 4/5 error-handling middleware. It logs formatted errors to the server console and sends a sanitized JSON response to the client, preventing stack trace leaks. ```typescript import express from 'express'; import { errorFormatter, setupConfig } from 'intellerror'; const app = express(); setupConfig({ webhookUrl: process.env.SLACK_WEBHOOK_URL }); app.get('/users/:id', async (req, res) => { const user = await db.users.findById(req.params.id); // may throw res.json(user); }); app.post('/orders', async (req, res) => { const order = await createOrder(req.body); // may throw res.status(201).json(order); }); // Must be registered AFTER all routes, with exactly 4 parameters app.use(errorFormatter()); app.listen(3000); // When /users/bad-id throws: // Server console: full formatted error with location + suggestions // Client receives: // HTTP 500 // { "error": { "name": "TypeError", "message": "Cannot read properties of undefined" } } ``` -------------------------------- ### parseStack(error) Source: https://context7.com/darshan1005/intellerror/llms.txt Parses an `Error` object's stack string into structured `ParsedStackFrame` objects. Each frame includes file path, method name, line/column, and flags for Node internals and `node_modules`. Automatically enriches frames with source map data when `.map` files are present. ```APIDOC ## `parseStack(error)` — Low-Level Stack Parser Parses an `Error` object's stack string into structured `ParsedStackFrame` objects. Each frame includes file path, method name, line/column, and flags for Node internals and `node_modules`. Automatically enriches frames with source map data when `.map` files are present. ### Parameters #### Path Parameters - **error** (Error) - Required - The error object to parse. ### Returns - **ParsedStackFrame[]** - An array of structured stack frame objects. - **file** (string) - The file path of the stack frame. - **methodName** (string) - The name of the method or function. - **lineNumber** (number) - The line number in the file. - **column** (number) - The column number in the file. - **isNodeInternal** (boolean) - True if the frame is part of Node.js internals. - **isNodeModule** (boolean) - True if the frame is part of a node_module. - **originalFile** (string) - The original file path (useful with source maps). - **originalLineNumber** (number) - The original line number (useful with source maps). - **originalColumn** (number) - The original column number (useful with source maps). ### Example Usage ```typescript import { parseStack, type ParsedStackFrame } from 'intellerror'; const err = new Error('Something went wrong'); const frames: ParsedStackFrame[] = parseStack(err); const userFrames = frames.filter(f => !f.isNodeInternal && !f.isNodeModule); console.log(userFrames[0]); ``` ``` -------------------------------- ### getErrorChain(error) Source: https://context7.com/darshan1005/intellerror/llms.txt Recursively walks the `Error.cause` chain and returns an array of `ErrorChain` objects (each with the error and its parsed stack frames). Supports the `Error.cause` pattern from Node.js 16.9+ and modern browsers. ```APIDOC ## `getErrorChain(error)` — Async Error Chain Traversal Recursively walks the `Error.cause` chain and returns an array of `ErrorChain` objects (each with the error and its parsed stack frames). Supports the `Error.cause` pattern from Node.js 16.9+ and modern browsers. ### Parameters #### Path Parameters - **error** (Error) - Required - The root error object to traverse. ### Returns - **ErrorChain[]** - An array of error chain objects. - **error** (Error) - The error object at this level of the chain. - **frames** (ParsedStackFrame[]) - The parsed stack frames for this error. ### Example Usage ```typescript import { getErrorChain, type ErrorChain } from 'intellerror'; const dbError = new Error('ECONNREFUSED 127.0.0.1:5432'); const serviceError = new Error('UserService: failed to load profile', { cause: dbError }); const apiError = new Error('GET /api/users/42 failed', { cause: serviceError }); const chain: ErrorChain[] = getErrorChain(apiError); chain.forEach((link, i) => { const indent = ' '.repeat(i); console.log(`${indent}[${i}] ${link.error.constructor.name}: ${link.error.message}`); console.log(`${indent} User frames: ${link.frames.filter(f => !f.isNodeInternal && !f.isNodeModule).length}`); }); ``` ``` -------------------------------- ### Format Error for Browser Console Source: https://github.com/darshan1005/intellerror/blob/main/README.md Format an error object for display in the browser console, ensuring proper CSS styling is applied using the spread operator. ```typescript import { formatErrorBrowser } from 'intellerror'; try { // ... } catch (err) { // MUST use the spread operator (...) for CSS styling console.log(...formatErrorBrowser(err)); } ``` -------------------------------- ### Format Error for Terminal Output Source: https://context7.com/darshan1005/intellerror/llms.txt Formats any Error instance into a colorized, human-readable string for Node.js terminal output. It includes detailed error information, source location, and a code snapshot. ```typescript import { formatError } from 'intellerror'; async function fetchUserFromDB(userId: string) { throw new Error('Connection refused (timeout after 5000ms)'); } async function getUser(userId: string) { try { await fetchUserFromDB(userId); } catch (cause) { throw new Error(`Failed to load user: ${userId}`, { cause }); } } try { await getUser('user_42'); } catch (err) { console.log(formatError(err)); } // Output (colorized in terminal): // ERROR Error: Failed to load user: user_42 // 2024-01-15T10:23:45.123Z | uptime: 2.3s | ID: f3a9b1c2 // // 📍 Location: // src/users/service.ts:9:11 ← YOUR CODE // // > 9 | throw new Error(`Failed to load user: ${userId}`, { cause }); // 8 | try { // 10 | } // // 🔗 Causes: // caused by: Error: Connection refused (timeout after 5000ms) // // 📦 Stack: // → src/users/service.ts:9:11 // (4 node internals hidden) ``` -------------------------------- ### Traverse Async Error Chains with `getErrorChain` Source: https://context7.com/darshan1005/intellerror/llms.txt Recursively walks the `Error.cause` chain to return an array of `ErrorChain` objects, each containing an error and its parsed stack frames. Supports Node.js 16.9+ `Error.cause` pattern. ```typescript import { getErrorChain, type ErrorChain } from 'intellerror'; // Build a multi-level error chain const dbError = new Error('ECONNREFUSED 127.0.0.1:5432'); const serviceError = new Error('UserService: failed to load profile', { cause: dbError }); const apiError = new Error('GET /api/users/42 failed', { cause: serviceError }); const chain: ErrorChain[] = getErrorChain(apiError); chain.forEach((link, i) => { const indent = ' '.repeat(i); console.log(`${indent}[${i}] ${link.error.constructor.name}: ${link.error.message}`); console.log(`${indent} User frames: ${link.frames.filter(f => !f.isNodeInternal && !f.isNodeModule).length}`); }); // [0] Error: GET /api/users/42 failed // User frames: 2 // [1] Error: UserService: failed to load profile // User frames: 1 // [2] Error: ECONNREFUSED 127.0.0.1:5432 // User frames: 1 ``` -------------------------------- ### Parse Stack Traces with Intellerror's `parseStack` Source: https://context7.com/darshan1005/intellerror/llms.txt Parses an Error object's stack string into structured `ParsedStackFrame` objects. Automatically enriches frames with source map data when `.map` files are present. Useful for filtering to user code frames. ```typescript import { parseStack, type ParsedStackFrame } from 'intellerror'; const err = new Error('Something went wrong'); const frames: ParsedStackFrame[] = parseStack(err); // Filter to only user code frames const userFrames = frames.filter(f => !f.isNodeInternal && !f.isNodeModule); console.log(userFrames[0]); // { // file: '/app/src/services/payment.ts', // methodName: 'processPayment', // lineNumber: 47, // column: 12, // isNodeInternal: false, // isNodeModule: false, // originalFile: 'src/services/payment.ts', // from source map // originalLineNumber: 31, // original TS line // originalColumn: 8 // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.