Back to skills

Production API Error Handling

Use this skill when building backend APIs to implement a centralized, secure, and informative error-handling strategy that prevents leaking sensitive data while helping clients debug.

BackendExpressFastAPINext.js (Route Handlers)NuxtDjango

Production API Error Handling

Category Version

Purpose

⚠IMPORTANT⚠This skill enforces strict exception isolation and deterministic state propagation. It prevents execution thread termination due to unhandled promise rejections and guarantees that sensitive internal memory states are stripped before network boundary transmission.

When to Use This Skill

⚠NOTE⚠Use this skill whenever you are writing API route logic, database queries, or integrating third-party services that could potentially fail.

What This Skill Prevents

This skill prevents:

  • Memory/State Leakage: Propagating raw V8 stack traces or SQL engine AST errors across the public network boundary.
  • Execution Thread Panic: Unhandled exceptions triggering a cascading halt of the entire Node.js/Python process memory space.
  • Schema Variance: Emitting inconsistent JSON geometries based on error origin (e.g., standardizing on RFC 9457).
  • Exception Swallowing: Generating silent fail states by catching exceptions without invoking the next error middleware or telemetry logger.

Core Principle

Exceptions MUST be intercepted at the execution boundary, stripped of internal memory topology, securely logged to telemetry, and serialized into deterministic, safe JSON schemas. Under no circumstances should internal implementation specifics traverse the boundary interface.

Research-Backed Rules

  • Centralized Execution Wrapper: Instantiate a global error handling abstraction. Distributed res.status().json() termination commands are strictly prohibited.
  • Operational vs. Syntax Classification: Define strict boundary logic between deterministic operational rejections (e.g., Auth schema failure) and non-deterministic process faults (e.g., Null pointers). Process faults MUST resolve to generic 500 outputs.
  • Production Stripping Constraint: Enforce strict environment variables (NODE_ENV === 'production') to trigger stack trace redaction algorithms on all outbound payloads.

Stack-Aware Guidance

Express / Node Guidance

Inject global termination middleware at the absolute terminus of the routing AST:

app.use((err, req, res, next) => {
  // Execute telemetry telemetry ingestion
  const status = err.statusCode || 500;
  const message = status === 500 ? 'Internal Server Error' : err.message;
  res.status(status).json({
    error: { message, status }
  });
});

Enforce express-async-handler abstractions to trap asynchronous promise rejection events.

Next.js Route Handlers Guidance

Next.js App Router API topologies lack global interception nets. Construct explicit wrapper decorators:

export async function withErrorHandler(handler: Function) {
  try {
    return await handler();
  } catch (error) {
    // Execute telemetry ingestion
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

Implementation Guidance

  1. Instantiate Exception Class: Extend native Error abstractions with deterministic statusCode and isOperational boolean flags.
  2. Execute Throw Sequences: Eject from business execution using new AppError(..., 404) rather than passing response dependencies.
  3. Intercept and Map: Global bounds MUST trap all exceptions, verify the isOperational boolean, and synthesize the output schema.
  4. Telemetry Ingestion: Pipe all trapped parameters to external aggregators (Sentry, Datadog) prior to connection closure.

Mathematical / Measurable Rules

  • Standardized Envelope (RFC 7807 / RFC 9457): All exception payloads MUST map to strict Problem Details schemas utilizing application/problem+json: { "type": "...", "title": "...", "status": 403, "detail": "...", "instance": "..." }

Quality Gates

Security Gate

  • Confirmed strict redaction of raw memory stack arrays in production environments.
  • Validated raw ORM/SQL error integers are suppressed and re-mapped.

Maintainability Gate

  • Validated centralized emission topology.
  • Asserted semantic HTTP status bounds (400, 401, 403, 404, 500).

Anti-Patterns to Avoid

  • Silent Rejection Swallowing:
    try { await db.save(); } catch (e) { /* null operation */ }
    
  • Status Code Degradation: Emitting generic 400 Bad Request states for core database engine failures (requires strict 500 mapping).

Agent Behavior Instructions

  1. Reject execution of any API AST lacking a comprehensive try/catch wrapper block.
  2. Initialize centralized termination nodes before parsing specific route architectures.
  3. Throw specific HTTP exceptions natively from domain-level singletons.

Final Review Checklist

  • V8 stack leaks blocked.
  • Deterministic JSON schema enforced.
  • Asynchronous rejections securely trapped.
  • Fully agent-optimized deterministic rules.