跳到正文
cccskills
免费在 GitHub 公开

error-handling-patterns

Production-grade error handling for Node.js/TypeScript backends. Error classes, HTTP mapping, logging, retry strategies.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md3.7 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Error Class Hierarchy

// Base application error
export class AppError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number = 500,
    public readonly context?: Record<string, unknown>
  ) {
    super(message);
    this.name = this.constructor.name;
    Error.captureStackTrace(this, this.constructor);
  }
}

// Domain-specific errors
export class NotFoundError extends AppError {
  constructor(resource: string, id: string) {
    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404, { resource, id });
  }
}

export class ValidationError extends AppError {
  constructor(field: string, message: string) {
    super(message, 'VALIDATION_ERROR', 400, { field });
  }
}

export class UnauthorizedError extends AppError {
  constructor(message = 'Unauthorized') {
    super(message, 'UNAUTHORIZED', 401);
  }
}

export class ConflictError extends AppError {
  constructor(resource: string) {
    super(`${resource} already exists`, 'CONFLICT', 409, { resource });
  }
}

Express Error Middleware

// Always the LAST middleware
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      error: {
        code: err.code,
        message: err.message,
        ...(process.env.NODE_ENV === 'development' ? { context: err.context } : {}),
      },
    });
  }

  // Unexpected error — log and return 500
  console.error('Unexpected error:', err);
  return res.status(500).json({
    error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' },
  });
});

Async Handler Wrapper

// Eliminates try/catch boilerplate in route handlers
export const asyncHandler = (fn: RequestHandler): RequestHandler =>
  (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', req.params.id);
  res.json(user);
}));

Retry Pattern

async function withRetry<T>(
  fn: () => Promise<T>,
  { maxAttempts = 3, delay = 100, backoff = 2 } = {}
): Promise<T> {
  let lastError: Error;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err) {
      lastError = err as Error;
      if (attempt === maxAttempts) break;
      await new Promise(r => setTimeout(r, delay * backoff ** (attempt - 1)));
    }
  }
  throw lastError!;
}

// Usage
const user = await withRetry(() => db.user.findUnique({ where: { id } }));

Result Type (No-throw Alternative)

type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

async function safeGetUser(id: string): Promise<Result<User>> {
  try {
    const user = await db.user.findUnique({ where: { id } });
    if (!user) return { ok: false, error: new NotFoundError('User', id) };
    return { ok: true, value: user };
  } catch (err) {
    return { ok: false, error: err as Error };
  }
}

Checklist

  • All error types extend AppError
  • HTTP status codes correctly mapped (400 client, 500 server)
  • Unexpected errors logged with context
  • Async routes wrapped (no unhandled rejections)
  • Sensitive data NOT in error responses (no stack traces in prod)

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

anoa

免费

Drive a real browser from the command line — open pages, snapshot the interactive elements as refs, click and fill by ref, read text, run JS, screenshot. Use when a task needs a live browser: checking a page renders, walking a login or checkout flow, scraping something that only exists after JavaScript runs, or reproducing a UI bug.

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

Run linters/typecheckers to calculate health score.

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

Comprehensive UI/UX compliance check (A11y, performance, responsive).

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

Infrastructure-first security audit (OWASP, secrets, dependencies).

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

auth

免费

Setup authentication flow (register, login, session/JWT, middleware)

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

Deep knowledge about deploying applications to AWS (EC2, ECS, S3, CloudFront, Cloud Run).

中文简介正在准备中。当前显示原文说明。

porcupine-md/jonggrang162026年9月15日 更新

查看 porcupine-md 的全部技能

报告此技能的问题