backend-error-handling
Skill9 starsChanged 42 days agoMITView on GitHub
Implement error-handling patterns: boundaries, toasts, one API error shape. Use when "error boundary", "error toast", or "standardize API errors". Plan-only audit → plan-error-handling. Sentry triage → debug-sentry-monitor.
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- kensaurus/skillsedited, first seen Oct 1, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- kensaurus/skills★ 937% same
Wrote their own version · 0
None found.
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.
In this repository165 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .cursor/rules/approved-plan-execution.mdcCursor rule
- .cursor/rules/skill-workflows.mdcCursor rule
- .cursor/rules/verification-before-completion.mdcCursor rule
- llms.txtllms.txt
- audit-accessibilitySkill
- audit-agent-speedSkill
- audit-analyticsSkill
- audit-auth-flowsSkill
- audit-backend-architectureSkill
- audit-bundle-sizeSkill
- audit-cicdSkill
- audit-codemod-safetySkill
- audit-code-qualitySkill
- audit-code-reviewSkill
- audit-db-schemaSkill
- audit-doctrineSkill
- audit-env-paritySkill
- audit-fe-apiSkill
- audit-gate-logicSkill
- audit-i18nSkill
- audit-infra-costSkill
- audit-langfuse-llmSkill
- audit-llm-securitySkill
- audit-monetization-iapSkill
- audit-payment-systemSkill
- audit-performanceSkill
- audit-realworldSkill
- audit-registry-listingSkill
- audit-resilienceSkill
- audit-responsiveSkill
- audit-securitySkill
- audit-skill-conflictsSkill
- audit-ui-statesSkill
- audit-uiux-design-systemSkill
- audit-ux-journeysSkill
- audit-uxSkill
- backend-db-performanceSkill
- backend-observabilitySkill
- backend-patternsSkill
- backend-realtimeSkill
- burndown-fullSkill
- complete-everythingSkill
- data-pipelineSkill
- data-visualizationSkill
- debug-errorSkill
- debug-fe-be-integrationSkill
- debug-sentry-monitorSkill
- deploy-npmSkill
- deploy-verifySkill
- design-apiSkill
- design-canvasSkill
- design-emailSkill
- design-frontendSkill
- design-generative-artSkill
- design-mobile-firstSkill
- design-motionSkill
- design-prdSkill
- design-systemSkill
- design-themeSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 80
Every error is caught at the lowest layer that can name it and surfaces upward as ActionResult or a typed API error, never as a raw throw …
- Very specific: line 103
Check the session; return UNAUTHORIZED with a "please sign in" message.
- Very specific: line 104
Run the mutation, revalidatePath, return { success: true, data }.
- Very specific: line 170
Use it for query errors (error + refetch) instead of ad-hoc red text per list.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Error Handling Skill
Degree of freedom: MIXED. Which layer and message [HIGH freedom];
existing-type/boundary probes [LOW freedom — run exactly].
How to reason
- Observe — existing error types, boundaries,
ActionResult/ApiError - Interpret — missing layer vs inconsistent shape vs swallowed catch
- Classify — reuse-existing / extend-codes / add-boundary / toast-only
- Severity — unhandled 500 on a mutation outranks a missing toast
Worked example
Observe:
createUserthrows PrismaP2002; UI shows a blank catch;ActionResultalready lives intypes/errors.ts. Interpret: known conflict is unmapped; no field/toast path. Classify: reuseActionResult+CONFLICT; toast the message; do not add a second error type. Verify: duplicate email returns{ success: false, error: { code: 'CONFLICT' } }; form alert shown.
Self-critique before reporting
- Reuse shape — searched
ActionResult/ApiError/error.tsxbefore adding a type - User-safe —
INTERNAL_ERRORis generic; PII is not in the client message - Layered — boundary + action result + toast, not toast-only
- Right owner — plan-only observability audit →
plan-error-handling; live Sentry triage →debug-sentry-monitor
Layered error handling for full-stack apps: one action-result shape, boundaries, and toasts.
When to Use
- Adding error handling to new features
- Improving error user experience
- Standardizing error responses
- Debugging error propagation
- Adding error monitoring
Check existing first [LOW freedom — run exactly]
Before adding ANY error handling, verify:
- Check for existing error types:
rg "type.*Error|interface.*Error" --type ts
rg "ActionResult|ApiError" --type ts- Check for existing error boundaries:
ls -la app/error.tsx app/global-error.tsx
rg "ErrorBoundary" --type tsx- Check for existing error utilities:
rg "formatError|handleError|reportError" --type ts
ls -la src/lib/errors* src/lib/error* 2>/dev/null # @/lib/errors- Check established error response patterns:
rg "success: false|error:" src/features/*/server/ --type ts | head -10Why: Inconsistent error handling confuses users and complicates debugging. Always follow established patterns.
Error Handling Layers [HIGH freedom]
- UI layer — error boundaries, form validation errors, toast notifications.
- Application layer — Server Action errors, API route errors, business-logic errors.
- Data layer — database errors, Zod validation errors, external API errors.
- Every error is caught at the lowest layer that can name it and surfaces upward as
ActionResultor a typed API error, never as a raw throw to the UI.
Layer diagram: references/server-patterns.md §Error handling layers.
Standard Error Types [HIGH freedom]
- One
AppError { code, message, details? };codeis machine-readable,messageis user-safe. ActionResult<T>is a discriminated union onsuccess; never return{ data, error }both-optional.- Error codes:
VALIDATION_ERROR,NOT_FOUND,UNAUTHORIZED,FORBIDDEN,CONFLICT,RATE_LIMITED,INTERNAL_ERROR.
// types/errors.ts
interface AppError { code: string; message: string; details?: unknown }
type ActionResult<T> =
| { success: true; data: T }
| { success: false; error: AppError }Full ErrorCode constant: references/server-patterns.md §Standard error types.
Server Action Error Handling [HIGH freedom]
safeParsetheFormData; returnVALIDATION_ERRORwithflatten().fieldErrorsasdetails.- Check the session; return
UNAUTHORIZEDwith a "please sign in" message. - Run the mutation,
revalidatePath, return{ success: true, data }. - Map known errors (Prisma
P2002→CONFLICTwith a specific message). - Log unknown errors server-side; return a generic
INTERNAL_ERRORmessage, never the stack.
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
return { success: false, error: { code: 'CONFLICT', message: 'A user with this email already exists' } }
}
console.error('createUser error:', error)
return { success: false, error: { code: 'INTERNAL_ERROR', message: 'Something went wrong. Please try again.' } }
}Full createUser action: references/server-patterns.md §Server Action error handling.
Form Error Display (React 19+) [HIGH freedom]
useActionState(createUser, null)for state;useFormStatusin a childSubmitButtonfor pending.- Field errors come from
state.error.details; render inline witharia-invalidandaria-describedby. - Non-validation errors render once in a
role="alert"banner above the fields. useOptimisticfor optimistic UI updates.
Full UserForm component: references/ui-patterns.md §Form error display.
React Error Boundaries [HIGH freedom]
app/error.tsxper page segment:'use client', receives{ error, reset }, logs inuseEffect, shows a "Try again" button.app/global-error.tsxfor the root: must render its own<html>and<body>.- Boundaries catch render errors only; async and event errors go through
ActionResultor TanStack Query.
// app/error.tsx
'use client'
export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
useEffect(() => { console.error('Page error:', error) }, [error])
return (
<div className="flex flex-col items-center justify-center min-h-[400px]">
<h2 className="text-xl font-semibold mb-4">Something went wrong</h2>
<button onClick={reset} className="px-4 py-2 bg-primary text-primary-foreground rounded-lg">Try again</button>
</div>
)
}Both boundaries in full: references/ui-patterns.md §React error boundaries.
API Route Error Handling [HIGH freedom]
- Same
{ error: { code, message, details? } }body shape for every non-2xx response. 400forVALIDATION_ERRORandINVALID_JSON(SyntaxErrorfromrequest.json()),201on create,500generic.- Log the route name with the error; never return stack traces.
Full POST /api/products handler: references/server-patterns.md §API route error handling.
TanStack Query Error Handling [HIGH freedom]
- In
queryFn/mutationFn, thrownew Error(body.error?.message ?? fallback)when!res.okso the UI gets the server message. retry: no retry on 401/403; up to 3 attempts otherwise.- Mutations:
onSuccessinvalidates the query key andtoast.success;onError→toast.error(error.message).
useProducts and useCreateProduct hooks: references/ui-patterns.md §TanStack Query error handling.
Error State UI Components [HIGH freedom]
- One reusable
ErrorState({ title, message, onRetry? }): icon, heading, message, optional retry button. - Use it for query errors (
error+refetch) instead of ad-hoc red text per list.
const { data, error, isLoading, refetch } = useProducts()
if (error) return <ErrorState title="Failed to load products" message={error.message} onRetry={() => refetch()} />Full ErrorState component: references/ui-patterns.md §Error state UI components.
Further reading
- Error Logging & Monitoring and the full checklist
- Server-side error patterns
- Client-side error patterns
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.

