node-error-handling
Node.js error handling patterns
What this skill does
# Node.js Error Handling Skill
Patterns for error handling in Node.js applications.
## Error Classes
### 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) {
super(`${resource} not found`, 'NOT_FOUND', 404)
}
}
class UnauthorizedError extends AppError {
constructor(message = 'Unauthorized') {
super(message, 'UNAUTHORIZED', 401)
}
}
class ForbiddenError extends AppError {
constructor(message = 'Forbidden') {
super(message, 'FORBIDDEN', 403)
}
}
class ConflictError extends AppError {
constructor(message: string) {
super(message, 'CONFLICT', 409)
}
}
```
### Error with Context
```typescript
class ContextualError extends Error {
public context: Record<string, any>
constructor(
message: string,
context: Record<string, any> = {},
public cause?: Error
) {
super(message)
this.name = 'ContextualError'
this.context = context
}
static wrap(error: Error, context: Record<string, any>): ContextualError {
return new ContextualError(error.message, context, error)
}
}
// Usage
throw ContextualError.wrap(dbError, {
operation: 'createUser',
userId: '123',
})
```
## Async Error Handling
### Express Error Middleware
```typescript
// Async handler wrapper
const asyncHandler = (fn: RequestHandler): RequestHandler => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next)
}
}
// Usage
router.get('/users/:id', asyncHandler(async (req, res) => {
const user = await userService.findById(req.params.id)
if (!user) throw new NotFoundError('User')
res.json(user)
}))
// Error middleware
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
// Log error
logger.error({
message: err.message,
code: err.code,
stack: err.stack,
path: req.path,
method: req.method,
})
// Handle operational errors
if (err instanceof AppError) {
return res.status(err.statusCode).json({
error: {
code: err.code,
message: err.message,
...(err instanceof ValidationError && { fields: err.fields }),
},
})
}
// Unknown errors
res.status(500).json({
error: {
code: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
},
})
}
app.use(errorHandler)
```
### Promise Rejection Handling
```typescript
// Unhandled rejection handler
process.on('unhandledRejection', (reason: Error, promise: Promise<any>) => {
console.error('Unhandled Rejection:', reason)
// Optionally exit
process.exit(1)
})
// Uncaught exception handler
process.on('uncaughtException', (error: Error) => {
console.error('Uncaught Exception:', error)
// Must exit - process is in undefined state
process.exit(1)
})
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down gracefully')
await server.close()
await database.disconnect()
process.exit(0)
})
```
## Error Boundaries
### Try-Catch Patterns
```typescript
// With cleanup
async function withResource<T>(fn: (resource: Resource) => Promise<T>): Promise<T> {
const resource = await acquireResource()
try {
return await fn(resource)
} finally {
await resource.release()
}
}
// Multiple operations
async function transactionalOperation() {
const tx = await db.beginTransaction()
try {
await tx.query('INSERT INTO users ...')
await tx.query('INSERT INTO profiles ...')
await tx.commit()
} catch (error) {
await tx.rollback()
throw error
}
}
// Partial success handling
async function processItems(items: Item[]): Promise<{
successful: Result[]
failed: Array<{ item: Item; error: Error }>
}> {
const successful: Result[] = []
const failed: Array<{ item: Item; error: Error }> = []
for (const item of items) {
try {
const result = await processItem(item)
successful.push(result)
} catch (error) {
failed.push({ item, error: error as Error })
}
}
return { successful, failed }
}
```
## Result Type Pattern
### Result Type
```typescript
type Result<T, E = Error> =
| { success: true; data: T }
| { success: false; error: E }
function ok<T>(data: T): Result<T, never> {
return { success: true, data }
}
function err<E>(error: E): Result<never, E> {
return { success: false, error }
}
// Usage
async function parseJSON<T>(text: string): Result<T, SyntaxError> {
try {
return ok(JSON.parse(text))
} catch (error) {
return err(error as SyntaxError)
}
}
const result = await parseJSON<User>(text)
if (result.success) {
console.log('User:', result.data)
} else {
console.error('Parse error:', result.error)
}
```
### Either Type
```typescript
class Either<L, R> {
private constructor(
private readonly left: L | null,
private readonly right: R | null
) {}
static left<L, R>(value: L): Either<L, R> {
return new Either(value, null)
}
static right<L, R>(value: R): Either<L, R> {
return new Either(null, value)
}
isLeft(): boolean {
return this.left !== null
}
isRight(): boolean {
return this.right !== null
}
map<T>(fn: (value: R) => T): Either<L, T> {
if (this.isRight()) {
return Either.right(fn(this.right!))
}
return Either.left(this.left!)
}
getOrElse(defaultValue: R): R {
return this.isRight() ? this.right! : defaultValue
}
}
```
## Logging Errors
### Structured Error Logging
```typescript
import pino from 'pino'
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
formatters: {
level: (label) => ({ level: label }),
},
})
function logError(error: Error, context: Record<string, any> = {}) {
logger.error({
err: {
name: error.name,
message: error.message,
stack: error.stack,
...(error instanceof AppError && {
code: error.code,
isOperational: error.isOperational,
}),
},
...context,
})
}
// Usage
try {
await riskyOperation()
} catch (error) {
logError(error as Error, {
operation: 'riskyOperation',
userId: user.id,
})
throw error
}
```
## Validation
### Input Validation
```typescript
import { z } from 'zod'
const userSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().positive().optional(),
})
function validateUser(data: unknown): User {
const result = userSchema.safeParse(data)
if (!result.success) {
const fields: Record<string, string> = {}
result.error.errors.forEach((err) => {
fields[err.path.join('.')] = err.message
})
throw new ValidationError('Invalid user data', fields)
}
return result.data
}
```
## Integration
Used by:
- `backend-developer` agent
- `fullstack-developer` agent
Related 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.