agentleFS
metarhiametarhia/metaskills/skills/error-handling/SKILL.md

error-handling

Skill61 starsChanged 8 months agoMITView on GitHub

Error handling and recovery in JavaScript/TypeScript and Node.js - try/catch, async errors, retry with exponential backoff, DomainError, error propagation across layers, process-level handlers, graceful shutdown. Use whenever writing code that retries, catches, wraps, or reports errors, or handles failures, timeouts, or shutdown

80 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use convention-learner, caching and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • codewithmukeshSkill

    convention-learner

    Detects and enforces project-specific coding conventions by analyzing existing codebase patterns. Learns naming conventions, folder structure, test organization, and coding style from the existing code. Load when: "conventions", "coding standards", "project patterns", "enforce style", "detect patterns", "learn conventions", "code consistency".

    Also in 3 projects that use this

  • wpankSkill

    caching

    Caching strategies, invalidation, eviction policies, HTTP caching, distributed caching, and anti-patterns. Use when designing cache layers, choosing eviction policies, debugging stale data, or optimizing read-heavy workloads.

    Also in 6 projects that use this

  • diego-tobalinaSkill

    logging

    Logging best practices for Java (SLF4J/Logback) and Node.js (Winston/Pino). Use for structured logging, log levels, and avoiding sensitive data exposure.

    Also in 12 projects that use this

  • codewithmukeshSkill

    opentelemetry

    OpenTelemetry observability for .NET 10 applications. Covers traces, metrics, and logs using the OpenTelemetry SDK with OTLP export. Includes custom ActivitySource, IMeterFactory metrics, resource configuration, and Aspire Dashboard integration. Load this skill when setting up distributed tracing, custom metrics, OTLP export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans", "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter", "Histogram", "Gauge", "telemetry", "observability", "distributed tracing", "OTEL", or "Aspire Dashboard".

    Also in 3 projects that use this

  • MovGP0Skill

    modern-csharp

    Modern C# style guidance for Bendex and MicroSea code changes, including primary constructors, expression-bodied members, var usage, target-typed new, lambdas, and pattern matching.

    Also in 3 projects that use this

  • MicrosoftSkill

    resilience

    Apply resilience patterns (retry, backoff, circuit breaking) when writing or reviewing code that makes outbound HTTP/REST calls, database operations, or any I/O that can experience transient failures. Use this skill when: (1) writing new code that calls external services or APIs, (2) reviewing code that uses fetch, HTTP clients, or service-to-service calls, (3) adding queue consumers or workers that interact with remote systems, (4) debugging intermittent failures in production.

    Also in 4 projects that use this

The file

We split this skill into the rules it gives an agent

5 rules. 0 are common, 4 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 64 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not expose internal error details to clients.

    line 64
  2. Distinctive:

    Use DomainError for business validation in API methods.

    line 69
  3. Distinctive:

    Never swallow errors silently.

    line 70
  4. Distinctive:

    Use retry with exponential backoff for transient failures (network, DB connections)

    line 72
  5. Very specific:

    Always handle both uncaughtException and unhandledRejection at process level

    line 73

“Common” is measured: kept by at least 6 in 10 of the 64 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Error Handling

Error classification

  • Programming errors: Bugs (TypeError, ReferenceError, assertion failures, etc.). Fix the code; do not catch and continue
  • Operational errors: Expected failures (network timeout, file not found, invalid input, etc.). Handle gracefully with recovery, escalation, user notification, or logging

Sync error handling

const parseInput = (input, defaultValue) => {
  try {
    const result = parse(input);
    return result;
  } catch (error) {
    console.error({ error });
    return defaultValue;
  }
};

Async error handling

const load = async (url) => {
  try {
    const data = await fetchData(url);
    return data;
  } catch (error) {
    if (error.code === 'ECONNREFUSED') return fallback();
    throw error;
  }
};

DomainError

Structured business errors with codes for the API layer:

({
  method: async ({ email }) => {
    const user = await domain.user.findByEmail(email);
    if (!user) return new DomainError('ENOTFOUND');
    return user;
  },
  errors: { ENOTFOUND: 'User not found' },
});

Domain layer throws plain errors; API layer translates to DomainError when needed.

Error propagation across layers

domain throws Error -> API catches -> returns DomainError(code) -> client gets structured error

Do not expose internal error details to clients; map to known error codes or general errors.

Conventions

  • Distinguish programmer vs operational errors; only recover from operational
  • Use DomainError for business validation in API methods; throw for programming bugs
  • Never swallow errors silently; always log or propagate
  • Implement graceful shutdown: stop accepting connections, drain existing, release resources
  • Use retry with exponential backoff for transient failures (network, DB connections)
  • Always handle both uncaughtException and unhandledRejection at process level

Retry pattern

const retry = async (fn, { attempts = 3, delay = 1000 } = {}) => {
  for (let i = 1; i < attempts; i++) {
    try {
      return await fn();
    } catch {
      const timeout = delay * 2 ** (i - 1);
      await new Promise((resolve) => setTimeout(resolve, timeout));
    }
  }
  return fn();
};

Process-level handlers

process.on('uncaughtException', (error) => {
  console.error('Uncaught:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection:', reason);
});

Log and exit on uncaughtException (state may be corrupted). Log unhandledRejection and consider it a bug to fix.

Graceful shutdown

Track connections and drain before exit:

const connections = new Map();

server.on('connection', (conn) => {
  const res = null;
  connections.set(conn, res);
  conn.on('close', () => connections.delete(conn));
});

const shutdown = () => {
  server.close(() => {
    freeResources();
    process.exit(0);
  });
  for (const entry of connections) {
    const conn = entry[0];
    const res = entry[1];
    if (res) res.end('Server shutting down');
    conn.destroy();
  }
};

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.