Error Handlingのロゴ

Error Handling

組織
MadAppGang
error-handling

Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

概要

公開者MadAppGang
リポジトリclaude-code
スキル名error-handling
スター
281
フォーク
26
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    MadAppGangがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Error Handling」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/MadAppGang/claude-code/tree/main/plugins/dev/skills/backend/error-handling
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/MadAppGang/claude-code.git /tmp/claude-code
mkdir -p .claude/skills
cp -r /tmp/claude-code/plugins/dev/skills/backend/error-handling .claude/skills/error-handling
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでError Handlingを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にError Handlingを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Error Handlingは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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;
  userId?: string;
  [key: string]: unknown;
}

const logger = {
  info: (message: string, context?: LogContext) => {
    console.log(JSON.stringify({ level: 'info', message, ...context }));
  },

  warn: (message: string, context?: LogContext) => {
    console.log(JSON.stringify({ level: 'warn', message, ...context }));
  },

  error: (message: string, context?: LogContext & { error?: string; stack?: string }) => {
    console.error(JSON.stringify({ level: 'error', message, ...context }));
  },
};

// Error logging middleware
function logErrors(error: Error, req: Request, res: Response, next: NextFunction) {
  logger.error('Request error', {
    requestId: req.headers['x-request-id'] as string,
    userId: req.user?.id,
    path: req.path,
    method: req.method,
    error: error.message,
    stack: error.stack,
  });
  next(error);
}

Graceful Shutdown

typescript
async function gracefulShutdown(signal: string) {
  logger.info('Shutdown signal received', { signal });

  // Stop accepting new requests
  server.close(() => {
    logger.info('HTTP server closed');
  });

  // Close database connections
  await db.close();
  logger.info('Database connections closed');

  // Close other resources
  await redis.quit();
  logger.info('Redis connection closed');

  process.exit(0);
}

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

// Handle uncaught errors
process.on('uncaughtException', (error) => {
  logger.error('Uncaught exception', { error: error.message, stack: error.stack });
  gracefulShutdown('uncaughtException');
});

process.on('unhandledRejection', (reason) => {
  logger.error('Unhandled rejection', { reason: String(reason) });
  gracefulShutdown('unhandledRejection');
});

Error handling patterns for robust backend services

よくある質問

AIスキル「Error Handling」では何ができますか?

Use when implementing custom error classes, error middleware, structured logging, retry logic, or graceful shutdown patterns in backend applications.

TypingMindでError Handlingを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Error Handlingはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにError Handlingをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/MadAppGang/claude-code/tree/main/plugins/dev/skills/backend/error-handlingを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Error Handlingを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Error Handlingで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもError Handlingを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Error Handling」は無料ですか?

はい。MadAppGangがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇