error-handling
Skill2 starsChanged 6 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.
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 60 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
- Very specific: line 233
NEVER catch (e) {} — empty catch is a bug factory
- Very specific: line 234
NEVER catch (e) { console.log(e) } — user sees nothing
- Distinctive: line 235
ALWAYS show user feedback for errors they caused (validation, auth)
- Distinctive: line 236
ALWAYS log + track unexpected errors (5xx, unknown)
- Distinctive: line 237
ALWAYS provide a recovery path (retry button, navigation, refresh)
- Distinctive: line 245
testing-strategy: Test error states, error boundary rendering
“Common” is measured: kept by at least 6 in 10 of the 60 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.
Files
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 Type | Display | When |
| Toast | Ephemeral notification, auto-dismiss | Mutation failures, network hiccups, non-blocking |
| Inline | Below the field or component | Validation errors, field-level issues |
| Banner | Top of section, dismissible | Partial page failure, degraded functionality |
| Full page | Replaces entire content | Unrecoverable 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
Other versions74 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 74
- microsoft/data-formulator★ 17ksame name
- epicenter-md/epicenter★ 4.8ksame name
- EpicenterHQ/epicenter★ 4.8ksame name
- NVIDIA-NeMo/RL★ 2.1ksame name
- software-mansion/react-native-executorch★ 1.8ksame name
- CloudAI-X/claude-workflow★ 1.4ksame name
- CloudAI-X/claude-workflow-v2★ 1.4ksame name
- alchemyplatform/aa-sdk★ 321same name
- Resgrid/Core★ 229same name
- DevelopersGlobal/ai-agent-skills★ 216same name
64 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use caching, logging and 9 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.
zebbernSkillcaching
Caching strategies — invalidation, TTL guidelines, cache keys, cache layers, and when not to cache. Use when implementing or reviewing caching logic.
Also in 5 projects that use this
diego-tobalinaSkilllogging
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 10 projects that use this
WelluxSkilltype-safety
Add or fix type annotations and enforce strict type safety. Invoke for: "add types", "type annotation", "TypeScript types", "Python type hints", "mypy", "tsc strict", "type errors", "any type", "unsafe cast", "missing types", "type this".
Also in 3 projects that use this
dbtlrSkilldependencies
Use when adding, evaluating, or updating Rust crate dependencies. Also use when considering whether to implement something yourself vs pulling in a library.
Also in 3 projects that use this
MicrosoftSkillresilience
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 3 projects that use this
OpenAISkillauth
Authentication integration guidance — Clerk (native Vercel Marketplace), Descope, and Auth0 setup for Next.js applications. Covers middleware auth patterns, sign-in/sign-up flows, and Marketplace provisioning. Use when implementing user authentication.
Also in 5 projects that use this
In this repository18 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- accessibilitySkill
- api-layerSkill
- auth-patternsSkill
- core-web-vitalsSkill
- css-architectureSkill
- design-intelligenceSkill
- frontend-designSkill
- i18nSkill
- monorepo-patternsSkill
- performance-optimizationSkill
- react-patternsSkill
- security-auditSkill
- seo-fundamentalsSkill
- state-managementSkill
- structured-dataSkill
- systematic-debuggingSkill
- testing-strategySkill
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
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.

