agentleFS
Piyush8296Piyush8296/claude-workspace/.claude/skills/error-handling/SKILL.md

error-handling

Skill2 starsChanged 7 months agoMITView on GitHub

Production error handling architecture for React and Next.js — Error boundary hierarchies, custom error classes, global error normalization, Sentry integration, fallback UI strategies, toast vs inline vs full-page error patterns, and error recovery. Use when building error UIs, setting up monitoring, or handling failures gracefully.

44 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use logging, load-testing and 5 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.
  • 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 5 projects that use this

  • DatabricksSkill

    load-testing

    Load test a Databricks App to find its maximum QPS. Use when: (1) User says 'load test', 'benchmark', 'QPS', 'throughput', or 'performance test', (2) User wants to find how many queries per second their app can handle, (3) User wants to set up load testing scripts for their agent, (4) User wants to view load test results/dashboard, (5) User wants to validate results or observe latency/error rate with MLflow tracing.

    Also in 3 projects that use this

  • JohnJBorenSkill

    ci-cd

    CI/CD pipeline design, GitHub Actions, testing automation, and deployment strategies

    Also in 5 projects that use this

  • pproencaSkill

    refactoring

    Code refactoring best practices based on Martin Fowler's catalog and Clean Code principles. This skill should be used when refactoring existing code, improving code structure, reducing complexity, eliminating code smells, or reviewing code for maintainability. Triggers on tasks involving extract method, rename, decompose conditional, reduce coupling, or improve readability.

    Also in 6 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 16 projects that use this

  • OpenAISkill

    observability

    Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.

    Also in 5 projects that use this

The file

We split this skill into the rules it gives an agent

6 rules. 0 are common, 4 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 37 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    NEVER catch (e) {} — empty catch is a bug factory

    line 233
  2. Very specific:

    NEVER catch (e) { console.log(e) } — user sees nothing

    line 234
  3. Distinctive:

    ALWAYS show user feedback for errors they caused (validation, auth)

    line 235
  4. Distinctive:

    ALWAYS log + track unexpected errors (5xx, unknown)

    line 236
  5. Distinctive:

    ALWAYS provide a recovery path (retry button, navigation, refresh)

    line 237
  6. Distinctive:

    testing-strategy: Test error states, error boundary rendering

    line 245

“Common” is measured: kept by at least 6 in 10 of the 37 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

The Error Handling Hierarchy

Errors should be caught at the closest meaningful boundary, not at the top of the tree.

App Error Boundary (crash recovery, "something went wrong" page)
  └─ Route Error Boundary (per-page, Next.js error.tsx)
       └─ Feature Error Boundary (per-feature section)
            └─ Component-level try/catch (inline error UI)
                 └─ Query/Mutation onError (toast notifications)

Custom Error Classes

// lib/errors.ts
export class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500,
    public isOperational: boolean = true,  // Expected vs unexpected
    public context?: Record<string, unknown>,
  ) {
    super(message);
    this.name = 'AppError';
  }
}

export class ValidationError extends AppError {
  constructor(message: string, public fields: Record<string, string[]>) {
    super(message, 'VALIDATION_ERROR', 400);
    this.name = 'ValidationError';
  }
}

export class AuthError extends AppError {
  constructor(message = 'Authentication required') {
    super(message, 'AUTH_ERROR', 401);
    this.name = 'AuthError';
  }
}

export class NotFoundError extends AppError {
  constructor(resource: string, id: string) {
    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404);
    this.name = 'NotFoundError';
  }
}

Error Normalizer

// lib/errors/normalize.ts
import { AppError } from './errors';

export function normalizeError(error: unknown): AppError {
  // Already normalized
  if (error instanceof AppError) return error;

  // API errors
  if (error instanceof Response || (error && typeof error === 'object' && 'status' in error)) {
    const e = error as { status: number; statusText?: string };
    return new AppError(
      e.statusText ?? 'Request failed',
      'API_ERROR',
      e.status,
    );
  }

  // Network errors
  if (error instanceof TypeError && error.message.includes('fetch')) {
    return new AppError('Network error — check your connection', 'NETWORK_ERROR', 0);
  }

  // Abort errors (not real errors)
  if (error instanceof DOMException && error.name === 'AbortError') {
    return new AppError('Request cancelled', 'ABORT_ERROR', 0, true);
  }

  // Unknown errors
  const message = error instanceof Error ? error.message : 'An unexpected error occurred';
  return new AppError(message, 'UNKNOWN_ERROR', 500, false);
}

Error Boundaries

Next.js App Router (error.tsx)

// app/error.tsx — catches errors in the entire app
'use client';

export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
  useEffect(() => {
    // Report to error tracker
    captureException(error);
  }, [error]);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-4">
      <h1 className="text-2xl font-bold">Something went wrong</h1>
      <p className="text-gray-600">{error.message}</p>
      <button onClick={reset} className="rounded bg-blue-600 px-4 py-2 text-white">
        Try again
      </button>
    </div>
  );
}
// app/dashboard/error.tsx — route-level, doesn't crash the entire app
'use client';

export default function DashboardError({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div className="rounded-lg border border-red-200 bg-red-50 p-6">
      <h2 className="font-semibold text-red-800">Dashboard failed to load</h2>
      <p className="text-sm text-red-600">{error.message}</p>
      <button onClick={reset} className="mt-3 text-sm text-red-700 underline">Retry</button>
    </div>
  );
}

React Error Boundary (Class Component)

// components/ErrorBoundary.tsx
import { Component, type ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback: ReactNode | ((error: Error, reset: () => void) => ReactNode);
  onError?: (error: Error, info: { componentStack: string }) => void;
}

interface State { error: Error | null; }

export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    this.props.onError?.(error, { componentStack: info.componentStack ?? '' });
  }

  reset = () => this.setState({ error: null });

  render() {
    if (this.state.error) {
      const { fallback } = this.props;
      return typeof fallback === 'function'
        ? fallback(this.state.error, this.reset)
        : fallback;
    }
    return this.props.children;
  }
}

Error Display Patterns

Error TypeDisplayWhen
ToastEphemeral notification, auto-dismissMutation failures, network hiccups, non-blocking
InlineBelow the field or componentValidation errors, field-level issues
BannerTop of section, dismissiblePartial page failure, degraded functionality
Full pageReplaces entire contentUnrecoverable errors, auth failures, 500s
// Toast: mutation error
const { mutate } = useMutation({
  mutationFn: updateUser,
  onError: (error) => {
    const normalized = normalizeError(error);
    toast.error(normalized.message);
    captureException(error);
  },
});

// Inline: form validation
{errors.email && (
  <p role="alert" className="text-sm text-red-600">{errors.email}</p>
)}

// Banner: degraded feature
{featureError && (
  <div role="alert" className="rounded border border-yellow-300 bg-yellow-50 p-3">
    <p className="text-sm text-yellow-800">Some features unavailable. <button onClick={retry}>Retry</button></p>
  </div>
)}

Error Tracking (Sentry)

// lib/monitoring.ts
import * as Sentry from '@sentry/nextjs';

export function captureException(error: unknown, context?: Record<string, unknown>) {
  const normalized = normalizeError(error);

  // Don't report operational errors (expected failures)
  if (normalized.isOperational && normalized.statusCode < 500) return;

  Sentry.captureException(error, {
    tags: { errorCode: normalized.code },
    extra: { ...normalized.context, ...context },
  });
}

export function setUserContext(user: { id: string; email: string }) {
  Sentry.setUser({ id: user.id, email: user.email });
}

Rules

  • NEVER catch (e) {} — empty catch is a bug factory
  • NEVER catch (e) { console.log(e) } — user sees nothing
  • ALWAYS show user feedback for errors they caused (validation, auth)
  • ALWAYS log + track unexpected errors (5xx, unknown)
  • ALWAYS provide a recovery path (retry button, navigation, refresh)
  • AbortError is not a real error — don't show it to users

Integration with Other Skills

  • api-layer: ApiError class, error normalization
  • react-patterns: Error state in the state handling order
  • accessibility: role="alert" on error messages, focus management
  • testing-strategy: Test error states, error boundary rendering

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.