JSPM

ai-error-solution

1.1.4
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 24
  • Score
    100M100P100Q72486F
  • License MIT

Lightweight Node.js error handler that uses OpenAI to provide explanations, causes, fixes, and documentation links for runtime errors

Package Exports

  • ai-error-solution

Readme

πŸ€– ai-error-solution

Lightweight, AI-powered error analysis for Node.js

Automatically capture runtime errors and get instant AI-generated explanations, causes, fixes, and documentation linksβ€”all in your console.

npm version License: MIT Node.js Version


✨ Features

  • 🎯 Zero Dependencies - Uses native curl via child_process (no heavy HTTP libraries)
  • πŸš€ Lightweight - Minimal package size, maximum efficiency
  • 🧠 AI-Powered Analysis - Leverages OpenAI to explain errors in plain English
  • πŸ” Privacy-First - No telemetry, no data storage, direct API calls only
  • ⚑ ESM Native - Modern ES Module support
  • 🎨 Beautiful Output - Clean, colorized console logging
  • πŸ› οΈ Production-Ready - Timeout handling, retries, graceful failures

πŸ“¦ Installation

npm install ai-error-solution

Requirements:

  • Node.js 18 or higher
  • curl installed on your system (usually pre-installed on macOS/Linux, available on Windows)
  • OpenAI API key (get one here)

πŸš€ Quick Start

1. Initialize Once

Set up the package with your OpenAI API key in your main application file:

import { initAutoErrorSolution, fixError } from 'ai-error-solution';

// Initialize with your API key (do this once at app startup)
initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-mini' // Optional: defaults to gpt-4o-mini
});

2. Use Anywhere

Wrap your error handling with fixError():

try {
  // Your code that might throw errors
  const result = riskyFunction();
} catch (err) {
  // Get AI-powered analysis
  await fixError(err);
}

3. Enjoy AI-Powered Debugging! πŸŽ‰

You'll see beautiful, formatted output like this:

================================================================================
❌ Error Detected: TypeError
Cannot read property 'map' of undefined

🧠 AI Explanation:
  This error occurs when you try to call the .map() method on a variable
  that is undefined. The JavaScript engine expected an array but received
  undefined instead.

⚠️  Likely Causes:
  - The variable was never initialized
  - An async function hasn't resolved yet
  - The API response didn't include expected data

πŸ”§ Suggested Fixes:
  - Add optional chaining: data?.map(...)
  - Provide a default value: (data || []).map(...)
  - Check existence first: if (data) { data.map(...) }

πŸ“š References:
  - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors
  - https://javascript.info/optional-chaining

πŸ’‘ Note: AI suggestions may not be 100% accurate. Always verify fixes before applying.
================================================================================

πŸ“– API Reference

initAutoErrorSolution(options)

Initialize the package with your OpenAI credentials. Must be called before using fixError().

Parameters:

  • options.apiKey (string, required) - Your OpenAI API key
  • options.model (string, optional) - OpenAI model to use (default: 'gpt-4o-mini')
  • options.timeout (number, optional) - API request timeout in milliseconds (default: 30000)
  • options.maxRetries (number, optional) - Maximum retry attempts (default: 1)

Example:

initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-mini',
  timeout: 30000,
  maxRetries: 2
});

fixError(error, options)

Analyze an error using OpenAI and display formatted results.

Parameters:

  • error (Error | string, required) - Error object or error message
  • options.silent (boolean, optional) - Return analysis without logging (default: false)

Returns:

  • Promise<null> - When logging to console (default)
  • Promise<Object> - When silent: true, returns analysis object

Example:

// Standard usage (logs to console)
try {
  dangerousCode();
} catch (err) {
  await fixError(err);
}

// Silent mode (returns data)
const analysis = await fixError(err, { silent: true });
console.log(analysis.analysis.explanation);

wrapWithErrorHandler(fn)

Wrap a function with automatic error handling.

Parameters:

  • fn (Function) - Function to wrap

Returns:

  • Function - Wrapped function that automatically calls fixError() on errors

Example:

const safeFunction = wrapWithErrorHandler(async () => {
  // Code that might throw
  return await riskyOperation();
});

await safeFunction(); // Errors automatically analyzed

setupGlobalHandler(options)

Register global handlers for uncaught exceptions and unhandled promise rejections.

Parameters:

  • options.exitOnError (boolean, optional) - Exit process after handling error (default: false)

Example:

setupGlobalHandler({ exitOnError: true });

// Now all uncaught errors will be automatically analyzed
throw new Error('This will be caught and analyzed');

πŸ” Environment Setup

  1. Install dotenv:
npm install dotenv
  1. Create .env:
OPENAI_API_KEY=sk-your-api-key-here
  1. Load in your app:
import 'dotenv/config';
import { initAutoErrorSolution } from 'ai-error-solution';

initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY
});

Using environment variables directly

# Linux/macOS
export OPENAI_API_KEY=sk-your-api-key-here
node app.js

# Windows (PowerShell)
$env:OPENAI_API_KEY="sk-your-api-key-here"
node app.js

# Windows (CMD)
set OPENAI_API_KEY=sk-your-api-key-here
node app.js

🎯 Use Cases

Express.js Error Middleware

import express from 'express';
import { initAutoErrorSolution, fixError } from 'ai-error-solution';

const app = express();

initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY
});

// Error handling middleware
app.use(async (err, req, res, next) => {
  await fixError(err);
  res.status(500).json({ error: 'Internal Server Error' });
});

Async Function Wrapper

const fetchUserData = wrapWithErrorHandler(async (userId) => {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
});

// Automatically analyzes errors
await fetchUserData(123);

Global Error Catching

import { initAutoErrorSolution, setupGlobalHandler } from 'ai-error-solution';

initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY
});

setupGlobalHandler({ exitOnError: false });

// All uncaught errors are now automatically analyzed

⚠️ Important Notes

Disclaimers

  • AI Accuracy: AI-generated suggestions may not always be correct. Always verify fixes before applying them to production code.
  • API Costs: Each error analysis makes an API call to OpenAI, which incurs costs based on your OpenAI plan.
  • Privacy: Error messages and stack traces are sent to OpenAI for analysis. Do not use in production if your errors may contain sensitive data.
  • curl Dependency: This package requires curl to be installed and accessible in your system PATH.

Best Practices

  • βœ… Use in development and debugging environments
  • βœ… Store API keys in environment variables (never commit them)
  • βœ… Set reasonable timeout values for production environments
  • βœ… Review AI suggestions before implementing fixes

πŸ—οΈ Architecture

This package is built with zero dependencies and uses:

  • ESM - Modern ES Module system
  • Native curl - No heavy HTTP libraries (axios, node-fetch, etc.)
  • child_process - Native Node.js process execution
  • Middleware pattern - One-time API key initialization

Why curl?

  • Minimal package size
  • No dependency vulnerabilities
  • Universal availability across platforms
  • Direct OpenAI API communication

πŸ› οΈ Troubleshooting

"curl is not installed or not in PATH"

Solution: Install curl on your system.

# macOS (via Homebrew)
brew install curl

# Ubuntu/Debian
sudo apt-get install curl

# Windows (via Chocolatey)
choco install curl

# Windows (built-in on Windows 10+)
# curl should already be available

"Package not initialized"

Solution: Make sure you call initAutoErrorSolution() before using fixError().

"OpenAI API request timed out"

Solution: Increase timeout or check your internet connection.

initAutoErrorSolution({
  apiKey: process.env.OPENAI_API_KEY,
  timeout: 60000 // 60 seconds
});

"OpenAI API error: Invalid API key"

Solution: Verify your API key is correct and has sufficient credits.


πŸ“„ License

MIT Β© [Your Name]


🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.



🌟 Why This Package?

Most error analysis tools either:

  • Require heavy dependencies (bloated package size)
  • Send data to third-party services (privacy concerns)
  • Auto-modify code (risky in production)

ai-error-solution is different:

  • βœ… Lightweight - No dependencies, tiny package size
  • βœ… Private - Direct API calls, no intermediaries
  • βœ… Safe - Never modifies your code
  • βœ… Transparent - Open source, audit the code yourself

Made with ❀️ for developers who value simplicity and privacy

Star ⭐ this project if you find it helpful!