error-handling
Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.
What this skill does
# Error Handling Patterns
## Overview
Backend error handling patterns for building robust and debuggable services.
## Error Types
### Custom Error Classes
```typescript
// Base application error
class AppError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number = 500,
public isOperational: boolean = true
) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
// Specific error types
class ValidationError extends AppError {
constructor(message: string, public fields?: Record<string, string>) {
super(message, 'VALIDATION_ERROR', 400);
}
}
class NotFoundError extends AppError {
constructor(resource: string, id?: string) {
super(
id ? `${resource} with id ${id} not found` : `${resource} not found`,
'NOT_FOUND',
404
);
}
}
class UnauthorizedError extends AppError {
constructor(message: string = 'Unauthorized') {
super(message, 'UNAUTHORIZED', 401);
}
}
class ForbiddenError extends AppError {
constructor(message: string = 'Forbidden') {
super(message, 'FORBIDDEN', 403);
}
}
class ConflictError extends AppError {
constructor(message: string) {
super(message, 'CONFLICT', 409);
}
}
class RateLimitError extends AppError {
constructor(public retryAfter: number) {
super('Too many requests', 'RATE_LIMIT', 429);
}
}
```
## Error Response Format
### Standard Format
```typescript
interface ErrorResponse {
error: {
code: string;
message: string;
details?: unknown;
stack?: string; // Only in development
};
meta: {
requestId: string;
timestamp: string;
};
}
function formatError(error: AppError, requestId: string): ErrorResponse {
const response: ErrorResponse = {
error: {
code: error.code,
message: error.message,
},
meta: {
requestId,
timestamp: new Date().toISOString(),
},
};
if (error instanceof ValidationError && error.fields) {
response.error.details = error.fields;
}
if (process.env.NODE_ENV === 'development') {
response.error.stack = error.stack;
}
return response;
}
```
### Example Responses
```json
// Validation error
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": {
"email": "Invalid email format",
"password": "Must be at least 8 characters"
}
},
"meta": {
"requestId": "req_abc123",
"timestamp": "2024-01-15T10:30:00Z"
}
}
// Not found error
{
"error": {
"code": "NOT_FOUND",
"message": "User with id 123 not found"
},
"meta": {
"requestId": "req_def456",
"timestamp": "2024-01-15T10:30:00Z"
}
}
// Server error (production)
{
"error": {
"code": "INTERNAL_ERROR",
"message": "An unexpected error occurred"
},
"meta": {
"requestId": "req_ghi789",
"timestamp": "2024-01-15T10:30:00Z"
}
}
```
## Error Handling Middleware
### Express Middleware
```typescript
import { Request, Response, NextFunction } from 'express';
// Async handler wrapper
function asyncHandler(fn: Function) {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
// Error handler middleware
function errorHandler(
error: Error,
req: Request,
res: Response,
next: NextFunction
) {
const requestId = req.headers['x-request-id'] as string || generateId();
// Log error
logger.error('Request failed', {
requestId,
error: error.message,
stack: error.stack,
path: req.path,
method: req.method,
});
// Handle known errors
if (error instanceof AppError) {
return res.status(error.statusCode).json(
formatError(error, requestId)
);
}
// Handle unknown errors
const internalError = new AppError(
process.env.NODE_ENV === 'production'
? 'An unexpected error occurred'
: error.message,
'INTERNAL_ERROR',
500,
false // Not operational
);
res.status(500).json(formatError(internalError, requestId));
}
// Usage
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = await userService.findById(req.params.id);
if (!user) throw new NotFoundError('User', req.params.id);
res.json({ data: user });
}));
app.use(errorHandler);
```
## Validation Errors
### Zod Validation
```typescript
import { z, ZodError } from 'zod';
const createUserSchema = z.object({
email: z.string().email('Invalid email format'),
password: z.string().min(8, 'Password must be at least 8 characters'),
name: z.string().min(2, 'Name must be at least 2 characters'),
});
function validateBody<T>(schema: z.Schema<T>) {
return (req: Request, res: Response, next: NextFunction) => {
try {
req.body = schema.parse(req.body);
next();
} catch (error) {
if (error instanceof ZodError) {
const fields = error.errors.reduce((acc, err) => {
acc[err.path.join('.')] = err.message;
return acc;
}, {} as Record<string, string>);
throw new ValidationError('Invalid input data', fields);
}
throw error;
}
};
}
// Usage
app.post('/users', validateBody(createUserSchema), createUser);
```
## Database Error Handling
```typescript
import { DatabaseError, UniqueConstraintError } from 'pg';
function handleDatabaseError(error: Error): AppError {
if (error instanceof UniqueConstraintError) {
return new ConflictError('Resource already exists');
}
if (error.message.includes('foreign key')) {
return new ValidationError('Referenced resource does not exist');
}
// Log unexpected database errors
logger.error('Database error', { error: error.message });
return new AppError('Database operation failed', 'DATABASE_ERROR', 500);
}
// Repository example
async function createUser(data: CreateUserInput): Promise<User> {
try {
return await db.users.create(data);
} catch (error) {
throw handleDatabaseError(error);
}
}
```
## External Service Errors
```typescript
class ExternalServiceError extends AppError {
constructor(
service: string,
public originalError?: Error
) {
super(
`External service ${service} failed`,
'EXTERNAL_SERVICE_ERROR',
503
);
}
}
async function callExternalAPI(url: string) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(5000), // 5 second timeout
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
throw new ExternalServiceError('API', new Error('Timeout'));
}
throw new ExternalServiceError('API', error);
}
}
```
## Retry Logic
```typescript
interface RetryOptions {
maxAttempts: number;
baseDelay: number;
maxDelay: number;
shouldRetry?: (error: Error) => boolean;
}
async function withRetry<T>(
fn: () => Promise<T>,
options: RetryOptions
): Promise<T> {
const { maxAttempts, baseDelay, maxDelay, shouldRetry } = options;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
const canRetry = shouldRetry?.(error) ?? true;
if (!canRetry || attempt === maxAttempts) {
throw error;
}
const delay = Math.min(
baseDelay * Math.pow(2, attempt - 1),
maxDelay
);
logger.warn('Retrying operation', {
attempt,
maxAttempts,
delay,
error: error.message,
});
await sleep(delay);
}
}
throw new Error('Unreachable');
}
// Usage
const result = await withRetry(
() => externalAPI.call(),
{
maxAttempts: 3,
baseDelay: 1000,
maxDelay: 10000,
shouldRetry: (error) => error instanceof ExternalServiceError,
}
);
```
## Logging Best Practices
```typescript
// Structured logging
interface LogContext {
requestId?: string;
userIRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.