Skip to content

logiccrafterdz/x402-error-handler

Repository files navigation

x402-error-handler

Production-ready, zero-runtime-dependency TypeScript library that transforms opaque HTTP 402 Payment Required responses into structured, machine-actionable error events suitable for autonomous agents, payment systems, and API integrators.

Features

  • Zero Dependencies: Pure TypeScript implementation
  • Machine-Actionable: Structured error codes with deterministic recovery paths
  • Cross-Platform: Works in Node.js ≥18, Bun, and modern browsers
  • Type-Safe: Full TypeScript support with strict type checking
  • Minimal Bundle: <3KB min+gzip
  • Telemetry Ready: Optional telemetry hooks for monitoring
  • Immutable Protocol: Fixed canonical error codes

Installation

npm install x402-error-handler

Quick Start

import { parseX402Error, formatError } from 'x402-error-handler';

const response = await fetch('https://api.example.com/paid-endpoint');

if (response.status === 402) {
  const errorContext = await parseX402Error(response);
  
  if (errorContext) {
    const formatted = formatError(errorContext);
    
    // Handle based on severity
    if (formatted.shouldStop) {
      console.log('Stop processing:', formatted.message);
    } else if (formatted.shouldRetry) {
      console.log('Retry with intent:', formatted.recoveryIntent);
    }
  }
}

Canonical Error Codes

Code Key Message Severity Recovery Intent
X402-001 INSUFFICIENT_FUNDS USDC balance too low on Base user fund_wallet
X402-002 INVALID_SIGNATURE Payment signature invalid or expired fatal
X402-003 PAYMENT_TIMEOUT Invoice expired. Retry with new nonce. retryable retry_with_nonce
X402-004 PAYMENT_CONFLICT Concurrent payment attempt for same resource retryable retry_with_backoff
X402-005 NETWORK_CONGESTION Base mempool congested. Auto-retry in progress. retryable retry_later
X402-999 UNKNOWN_402 Unrecognized 402 response. Inspect raw headers/body. debug

API Reference

parseX402Error(response: ResponseLike): Promise<ErrorContext | null>

Parses an HTTP 402 response and extracts x402 error information.

formatError(context: ErrorContext): FormattedError

Formats an error context into a machine-actionable error with retry/stop logic.

createX402Handler(options?: HandlerOptions): X402Handler

Creates a handler instance with optional telemetry.

Severity-Based Behavior

Severity shouldRetry shouldStop Action
fatal false true Stop immediately
retryable true false Retry with backoff
user false true Wallet action required
debug false false Log and continue

TypeScript Support

Full type definitions included:

interface ErrorContext {
  code: string;
  message: string;
  severity: 'fatal' | 'retryable' | 'user' | 'debug';
  recoveryIntent: 'fund_wallet' | 'retry_with_nonce' | 'retry_with_backoff' | 'retry_later' | null;
  raw?: any;
}

interface FormattedError {
  code: string;
  message: string;
  severity: Severity;
  recoveryIntent: RecoveryIntent;
  shouldRetry: boolean;
  shouldStop: boolean;
  metadata?: Record<string, any>;
}

Examples

See the examples directory for complete usage examples.

Development

# Install dependencies
npm install

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Build library
npm run build

# Type check
npm run typecheck

# Check bundle size
npm run size

Contact

License

MIT