Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问clear审计通过

error-handling错误处理

Agent Skill

error-handling 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,042

周安装

43

GitHub Stars

2

下载量

341
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:error-handling(错误处理)
来源仓库:https://github.com/pluginagentmarketplace/custom-plugin-nodejs
仓库路径:skills/error-handling
安装命令:
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill error-handling
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill error-handling

简介

用于记录任务执行中的错误与经验沉淀。

  • 适合持续修正 Agent 行为并积累能力缺口。
  • 需用户提供明确反馈以驱动模型改进。
  • 不自动修改系统配置或生产数据。error-handling 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 安装前请确认本地是否有写入权限。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Node.js Error Handling Skill

Master error handling patterns for building resilient Node.js applications that fail gracefully and provide meaningful feedback.

Quick Start

Error handling in 4 layers:

  1. Custom Error Classes - Typed, informative errors
  2. Try/Catch Patterns - Sync and async handling
  3. Express Middleware - Centralized API errors
  4. Process Handlers - Uncaught exceptions

Core Concepts

Custom Error Classes

// Base application error
class AppError extends Error {
  constructor(message, statusCode, code) {
    super(message);
    this.statusCode = statusCode;
    this.code = code;
    this.isOperational = true;
    Error.captureStackTrace(this, this.constructor);
  }
}

// Specific error types
class ValidationError extends AppError {
  constructor(message, details = []) {
    super(message, 400, 'VALIDATION_ERROR');
    this.details = details;
  }
}

class NotFoundError extends AppError {
  constructor(resource = 'Resource') {
    super(`${resource} not found`, 404, 'NOT_FOUND');
  }
}

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

class ForbiddenError extends AppError {
  constructor(message = 'Access denied') {
    super(message, 403, 'FORBIDDEN');
  }
}

Async Error Handling

// Async wrapper for Express routes
const asyncHandler = (fn) => (req, res, next) => {
  Promise.resolve(fn(req, res, next)).catch(next);
};

// Usage
router.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);
  if (!user) throw new NotFoundError('User');
  res.json(user);
}));

Express Error Middleware

const errorHandler = (err, req, res, next) => {
  // Log error
  logger.error({
    message: err.message,
    stack: err.stack,
    code: err.code,
    url: req.originalUrl
  });

  // Handle operational errors
  if (err.isOperational) {
    return res.status(err.statusCode).json({
      success: false,
      error: {
        message: err.message,
        code: err.code,
        ...(err.details && { details: err.details })
      }
    });
  }

  // Production: hide internal errors
  if (process.env.NODE_ENV === 'production') {
    return res.status(500).json({
      success: false,
      error: { message: 'Internal server error', code: 'INTERNAL_ERROR' }
    });
  }

  // Development: show stack
  res.status(500).json({
    success: false,
    error: { message: err.message, stack: err.stack }
  });
};

Learning Path

Beginner (1-2 weeks)

  • ✅ Understand Error types
  • ✅ Try/catch for sync code
  • ✅ Promise.catch() handling
  • ✅ Basic Express error middleware

Intermediate (3-4 weeks)

  • ✅ Custom error classes
  • ✅ Async error wrapper
  • ✅ Centralized error handling
  • ✅ Error logging with Winston

Advanced (5-6 weeks)

  • ✅ Production error monitoring
  • ✅ Graceful shutdown
  • ✅ Circuit breaker patterns
  • ✅ Error recovery strategies

Process-Level Error Handling

// Uncaught exceptions
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  logger.fatal({ error }, 'Uncaught exception');
  process.exit(1);
});

// Unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection:', reason);
  logger.error({ reason }, 'Unhandled rejection');
});

// Graceful shutdown
process.on('SIGTERM', async () => {
  console.log('SIGTERM received. Graceful shutdown...');
  server.close(() => console.log('HTTP server closed'));
  await mongoose.connection.close();
  process.exit(0);
});

Retry with Exponential Backoff

async function retryOperation(fn, options = {}) {
  const { maxRetries = 3, delay = 1000, backoff = 2 } = options;
  let lastError;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      if (attempt === maxRetries) throw error;

      const waitTime = delay * Math.pow(backoff, attempt - 1);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
  throw lastError;
}

Error Response Format

// Success
{ "success": true, "data": { ... } }

// Error
{
  "success": false,
  "error": {
    "message": "User not found",
    "code": "NOT_FOUND",
    "details": [],
    "timestamp": "2024-01-15T10:30:00.000Z"
  }
}

Unit Test Template

describe('Error Handling', () => {
  describe('ValidationError', () => {
    it('should create error with correct properties', () => {
      const error = new ValidationError('Invalid input', [
        { field: 'email', message: 'Required' }
      ]);

      expect(error.statusCode).toBe(400);
      expect(error.code).toBe('VALIDATION_ERROR');
      expect(error.isOperational).toBe(true);
    });
  });

  describe('asyncHandler', () => {
    it('should catch async errors', async () => {
      const mockNext = jest.fn();
      const handler = asyncHandler(async () => {
        throw new Error('Test error');
      });

      await handler({}, {}, mockNext);
      expect(mockNext).toHaveBeenCalledWith(expect.any(Error));
    });
  });
});

Troubleshooting

ProblemCauseSolution
Unhandled rejection warningsMissing.catch()Add process handler + local catches
Error swallowed silentlyEmpty catch blockLog or rethrow errors
Stack trace missingError.captureStackTrace not calledUse AppError base class
Memory leak from errorsStoring error referencesUse WeakMap or clean up

When to Use

Use proper error handling when:

  • Building production Node.js applications
  • Creating REST APIs with Express
  • Handling database operations
  • Processing external API calls
  • Implementing retry logic

Related Skills

  • Express REST API (API error responses)
  • Async Programming (promise rejections)
  • Testing & Debugging (error testing)

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

28.16%
按下载量换算96

trae

24.62%
按下载量换算84

OpenCode

18.52%
按下载量换算63

Gemini CLI

11.96%
按下载量换算41

windsurf

7.51%
按下载量换算26

Codex

3.34%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills