| name | error-handling-patterns |
| description | Design robust error handling strategies including try-catch blocks, custom error classes, error boundaries, graceful degradation, and comprehensive logging. Use when implementing exception handling, creating custom error types, setting up error boundaries in React, designing error response formats for APIs, implementing retry logic, handling async errors and promise rejections, logging errors for monitoring, creating user-friendly error messages, or building fault-tolerant systems that fail gracefully. |
Error Handling Patterns - Robust Error Management
When to use this skill
- Implementing try-catch blocks for error handling
- Creating custom error classes with specific error codes
- Setting up React Error Boundaries for UI error recovery
- Designing consistent API error response formats
- Handling async errors and promise rejections
- Implementing retry logic with exponential backoff
- Logging errors for monitoring and debugging
- Creating user-friendly error messages
- Building graceful degradation for failed services
- Handling validation errors consistently
- Implementing error tracking with Sentry or similar
- Designing fault-tolerant systems
When to use this skill
- Implementing error handling, designing fault-tolerant systems, debugging production issues, or improving error messages.
- When working on related tasks or features
- During development that requires this expertise
Use when: Implementing error handling, designing fault-tolerant systems, debugging production issues, or improving error messages.
Core Principles
- Fail Fast, Fail Loud - Detect errors early, make them visible
- Never Swallow Errors - Always log or handle appropriately
- Actionable Error Messages - Tell users what went wrong and how to fix it
- Type-Safe Errors - Use custom error classes
- Graceful Degradation - System remains functional despite errors
Error Types
1. Custom Error Classes
export class AppError extends Error {
constructor(
message: string,
public statusCode: number = 500,
public code: string = 'INTERNAL_ERROR',
public isOperational: boolean = true
) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
export class ValidationError extends AppError {
constructor(message: string, public fields?: Record<string, string>) {
super(message, 400, 'VALIDATION_ERROR');
}
}
export class {
() {
(, , );
}
}
{
() {
(message, , );
}
}
{
() {
(message, , );
}
}
{
() {
(message, , );
}
}
{
() {
(, , );
}
}
(, {
:
});
(, userId);
();
2. Result Type Pattern
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E };
function divide(a: number, b: number): Result<number> {
if (b === 0) {
return {
success: false,
error: new Error('Division by zero')
};
}
return {
success: true,
data: a / b
};
}
const result = divide(10, 2);
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}
async function fetchUser(: ): <<>> {
{
user = db..(id);
(!user) {
{
: ,
: (, id)
};
}
{ : , : user };
} (error) {
{
: ,
: error ? error : ()
};
}
}
Express Error Handling
1. Centralized Error Handler
import { Request, Response, NextFunction } from 'express';
export function errorHandler(
err: Error,
req: Request,
res: Response,
next: NextFunction
) {
console.error({
error: err.message,
stack: err.stack,
url: req.url,
method: req.method,
body: req.body,
user: req.user?.id
});
if (process.env.NODE_ENV === 'production') {
Sentry.captureException(err);
}
if (err instanceof AppError) {
return res.status(err.statusCode).json({
error: {
code: err.,
: err.,
...(err && { : err. })
}
});
}
(err. === ) {
(err. === ) {
res.().({
: {
: ,
:
}
});
}
}
res.().({
: {
: ,
: process.. ===
?
: err.
}
});
}
app.(errorHandler);
2. Async Error Wrapper
function asyncHandler(fn: Function) {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = await userService.getUser(req.params.id);
if (!user) {
throw new NotFoundError('User', req.params.id);
}
res.json(user);
}));
import 'express-async-errors';
app.get('/users/:id', async (req, res) => {
const user = await userService.getUser(req.params.id);
if (!user) {
(, req..);
}
res.(user);
});
React Error Handling
1. Error Boundaries
import React, { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: (error: Error) => ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
state: State = {
hasError: false,
error: null
};
static getDerivedStateFromError(error: Error): State {
return {
hasError: true,
error
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.(, error, errorInfo);
.(error, {
: {
: {
: errorInfo.
}
}
});
}
() {
(..) {
(..) {
..(..!);
}
(
);
}
..;
}
}
() {
(
);
}
2. Async Error Handling
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchUser() {
try {
setLoading(true);
setError(null);
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Failed to fetch user: ${response.statusText}`);
}
const data = await response.json();
setUser(data);
} catch (err) {
setError(err instanceof Error ? err : new Error());
} {
();
}
}
();
}, [userId]);
(loading) ;
(error) ;
(!user) ;
;
}
{ useQuery } ;
() {
{ : user, isLoading, error } = ({
: [, userId],
: (userId),
: ,
: .( * ** attemptIndex, )
});
(isLoading) ;
(error) ;
(!user) ;
;
}
Retry Strategies
1. Exponential Backoff
async function fetchWithRetry<T>(
fn: () => Promise<T>,
options: {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
} = {}
): Promise<T> {
const {
maxRetries = 3,
baseDelay = 1000,
maxDelay = 30000
} = options;
let lastError: Error;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error instanceof Error ? error : new Error('Unknown error');
if (attempt === maxRetries) {
break;
}
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
console.log(`Attempt ${attempt + } failed, retrying in ms...`);
( (resolve, delay));
}
}
lastError!;
}
user = ( ().( r.()), {
: ,
:
});
2. Circuit Breaker
class CircuitBreaker {
private failureCount = 0;
private successCount = 0;
private nextAttempt = Date.now();
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';
constructor(
private threshold: number = 5,
private timeout: number = 60000,
private monitoringPeriod: number = 120000
) {}
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'OPEN') {
if (Date.now() < this.nextAttempt) {
throw new Error('Circuit breaker is OPEN');
}
this.state = 'HALF_OPEN';
}
try {
const result = ();
.();
result;
} (error) {
.();
error;
}
}
() {
. = ;
(. === ) {
. = ;
. = ;
}
}
() {
.++;
. = ;
(. >= .) {
. = ;
. = .() + .;
.();
}
}
}
breaker = (, );
{
data = breaker.( ());
} (error) {
.();
}
Error Monitoring
1. Sentry Integration
import * as Sentry from '@sentry/node';
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV,
tracesSampleRate: 1.0,
beforeSend(event, hint) {
if (event.request) {
delete event.request.cookies;
delete event.request.headers?.authorization;
}
return event;
}
});
Sentry.setUser({
id: user.id,
email: user.email
});
Sentry.setContext('order', {
id: order.id,
total: order.total
});
try {
await processPayment(order);
} catch (error) {
Sentry.captureException(error, {
tags: {
: ,
: order.
},
: {
: order.,
: order.
}
});
error;
}
2. Structured Logging
import winston from 'winston';
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.error('Payment failed', {
error: error.message,
stack: error.stack,
userId: user.id,
orderId: order.id,
amount: order.total
});
const paymentLogger = logger.child({ service: 'payment' });
paymentLogger.(, { : tx. });
Error Handling Checklist
Error Detection:
□ All async functions wrapped in try/catch
□ Unhandled promise rejections caught
□ Input validation at entry points
□ Database errors handled
□ Network errors handled
Error Types:
□ Custom error classes for different scenarios
□ Operational vs programmer errors distinguished
□ HTTP status codes appropriate
□ Error codes consistent across API
Error Messages:
□ User-friendly messages (no technical jargon)
□ Actionable (tell user what to do)
□ No sensitive data exposed
□ Helpful for debugging in development
□ Generic in production
Error Recovery:
□ Retry logic for transient failures
□ Circuit breakers for external services
□ Graceful degradation strategies
□ Fallback values where appropriate
□ Cleanup in finally blocks
Monitoring:
□ Error tracking service configured (Sentry, etc.)
□ Structured logging implemented
□ Error rates monitored
□ Alerts for critical errors
□ Context included in error reports
Resources
Remember: Good error handling makes debugging easier, users happier, and systems more reliable. Fail gracefully, log thoroughly, and always provide actionable feedback.