error-handling
Error handling patterns using wellcrafted trySync and tryAsync. Use when writing error handling code, using try-catch blocks, or working with Result types and graceful error recovery.
Install
mkdir -p .claude/skills/error-handling && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3309" && unzip -o skill.zip -d .claude/skills/error-handling && rm skill.zipInstalls to .claude/skills/error-handling
About this skill
Error Handling with wellcrafted trySync and tryAsync
When to Apply This Skill
Use this pattern when you need to:
- Replace recoverable
try-catchblocks withtrySyncortryAsync. - Handle fallback success paths via
Ok(...)and propagate failures withErr(...). - Wrap caught exceptions as
causefor typed domain error constructors. - Refactor nested error branches into immediate-return linear control flow.
- Convert handler failures into HTTP status responses with explicit guards.
References
Load these on demand based on what you're working on:
- If working with wrapping boundaries, minimal vs extended wrapping, or immediate-return control flow, read references/wrapping-patterns.md
- If working with real-world codebase examples and wrapping scenario guidelines, read references/real-world-examples.md
- If working with HTTP route handlers and status-response error conversion, read references/http-handlers.md
Use trySync/tryAsync Instead of try-catch for Graceful Error Handling
When handling errors that can be gracefully recovered from, use trySync (for synchronous code) or tryAsync (for asynchronous code) from wellcrafted instead of traditional try-catch blocks. This provides better type safety and explicit error handling.
Related Skills: See
services-layerskill fordefineErrorspatterns and service architecture. Seequery-layerskill for error transformation toWhisperingError.
The Pattern
import { trySync, tryAsync, Ok, Err } from 'wellcrafted/result';
// SYNCHRONOUS: Use trySync for sync operations
const { data, error } = trySync({
try: () => {
const parsed = JSON.parse(jsonString);
return validateData(parsed); // Automatically wrapped in Ok()
},
catch: (e) => {
// Gracefully handle parsing/validation errors
console.log('Using default configuration');
return Ok(defaultConfig); // Return Ok with fallback
},
});
// ASYNCHRONOUS: Use tryAsync for async operations
await tryAsync({
try: async () => {
const child = new Child(session.pid);
await child.kill();
console.log(`Process killed successfully`);
},
catch: (e) => {
// Gracefully handle the error
console.log(`Process was already terminated`);
return Ok(undefined); // Return Ok(undefined) for void functions
},
});
// Both support the same catch patterns
const syncResult = trySync({
try: () => riskyOperation(),
catch: (error) => {
// For recoverable errors, return Ok with fallback value
return Ok('fallback-value');
// For unrecoverable errors, pass the raw cause — the constructor handles extractErrorMessage
return CompletionError.ConnectionFailed({ cause: error });
},
});
Key Rules
- Choose the right function - Use
trySyncfor synchronous code,tryAsyncfor asynchronous code - Always await tryAsync - Unlike try-catch, tryAsync returns a Promise and must be awaited
- trySync returns immediately - No await needed for synchronous operations
- Match return types - If the try block returns
T, the catch should returnOk<T>for graceful handling - Use Ok(undefined) for void - When the function returns void, use
Ok(undefined)in the catch - Return Err for propagation - Use custom error constructors that return
Errwhen you want to propagate the error - Transform cause in the constructor, not the call site - When wrapping a caught error, pass the raw error as
cause: unknownand let thedefineErrorsconstructor callextractErrorMessage(cause)inside its message template. Don't callextractErrorMessageat the call site. This centralizes message extraction where the message is composed:
// ✅ GOOD: cause: error at call site, extractErrorMessage in constructor
catch: (error) => CompletionError.ConnectionFailed({ cause: error })
// ❌ BAD: extractErrorMessage at call site, string passed to constructor
catch: (error) => CompletionError.ConnectionFailed({ underlyingError: extractErrorMessage(error) })
- CRITICAL: Wrap destructured errors with Err() - When you destructure
{ data, error }from tryAsync/trySync, theerrorvariable is the raw error value, NOT wrapped inErr. You must wrap it before returning:
// WRONG - error is just the raw error value, not a Result
const { data, error } = await tryAsync({...});
if (error) return error; // TYPE ERROR: Returns raw error, not Result
// CORRECT - wrap with Err() to return a proper Result
const { data, error } = await tryAsync({...});
if (error) return Err(error); // Returns Err<CustomError>
This is different from returning the entire result object:
// This is also correct - userResult is already a Result type
const userResult = await tryAsync({...});
if (userResult.error) return userResult; // Returns the full Result
Examples
// SYNCHRONOUS: JSON parsing with fallback
const { data: config } = trySync({
try: () => JSON.parse(configString),
catch: (e) => {
console.log('Invalid config, using defaults');
return Ok({ theme: 'dark', autoSave: true });
},
});
// SYNCHRONOUS: File system check
const { data: exists } = trySync({
try: () => fs.existsSync(path),
catch: () => Ok(false), // Assume doesn't exist if check fails
});
// ASYNCHRONOUS: Graceful process termination
await tryAsync({
try: async () => {
await process.kill();
},
catch: (e) => {
console.log('Process already dead, continuing...');
return Ok(undefined);
},
});
// ASYNCHRONOUS: File operations with fallback
const { data: content } = await tryAsync({
try: () => readFile(path),
catch: (e) => {
console.log('File not found, using default');
return Ok('default content');
},
});
// EITHER: Error propagation (works with both)
// Pass the raw caught error as cause — the defineErrors constructor calls extractErrorMessage
const { data, error } = await tryAsync({
try: () => criticalOperation(),
catch: (error) =>
CompletionError.ConnectionFailed({ cause: error }),
});
if (error) return Err(error);
When to Use trySync vs tryAsync vs try-catch
-
Use trySync when:
- Working with synchronous operations (JSON parsing, validation, calculations)
- You need immediate Result types without promises
- Handling errors in synchronous utility functions
- Working with filesystem sync operations
-
Use tryAsync when:
- Working with async/await operations
- Making network requests or database calls
- Reading/writing files asynchronously
- Any operation that returns a Promise
-
Use traditional try-catch when:
- In module-level initialization code where you can't await
- For simple fire-and-forget operations
- When you're outside of a function context
- When integrating with code that expects thrown exceptions
More by EpicenterHQ
View all skills by EpicenterHQ →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversIntegrate with Google Drive and GCloud Storage via Google Cloud Platform for seamless access to Compute Engine, BigQuery
Baidu Search provides fast web search using baidu.com. Retrieve results and webpage content with robust error handling a
Generate images from text prompts using ModelScope Qwen-Image with format auto-detection and robust multilingual support
Kokoro Speech: natural-sounding Kokoro TTS with customizable voices and playback speed — fast, reliable text-to-speech w
Specif-ai ensures secure web API access and robust error handling, making it a top choice among API security companies f
Use Chrome DevTools for web site test speed, debugging, and performance analysis. The essential chrome developer tools f
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.