Advanced

Error Handling Design Patterns dengan Claude Code

Pelajari tentang error handling design patterns menggunakan Claude Code. Dilengkapi tips praktis dan contoh kode.

errorハンドリングの設計 dengan Claude Code: peningkatan

tepatなerrorハンドリング aplikasi robust性 直結.Claude Code 使えば、type safety 一貫性 adaerrorハンドリングpola efisien implementasi bisa dilakukan.

設計 カスタムerrorclass

> aplikasi全体 dengan 使うカスタムerrorclass 設計して。
> HTTPステータスコード dan dukungan、errorコード、
> pengguna向けpesan 含めて。
// errors/base.ts
export abstract class AppError extends Error {
  abstract readonly statusCode: number;
  abstract readonly code: string;
  readonly isOperational: boolean;

  constructor(message: string, isOperational = true) {
    super(message);
    this.name = this.constructor.name;
    this.isOperational = isOperational;
    Error.captureStackTrace(this, this.constructor);
  }

  toJSON() {
    return {
      error: {
        code: this.code,
        message: this.message,
        ...(process.env.NODE_ENV === "development" && { stack: this.stack }),
      },
    };
  }
}

// errors/http.ts
export class NotFoundError extends AppError {
  readonly statusCode = 404;
  readonly code = "NOT_FOUND";

  constructor(resource: string, id?: string) {
    super(id ? `${resource}(${id}) 見つかりません` : `${resource} 見つかりません`);
  }
}

export class ValidationError extends AppError {
  readonly statusCode = 400;
  readonly code = "VALIDATION_ERROR";
  readonly fields: Record<string, string[]>;

  constructor(fields: Record<string, string[]>) {
    super("validasierror あります");
    this.fields = fields;
  }

  toJSON() {
    return {
      error: {
        code: this.code,
        message: this.message,
        fields: this.fields,
      },
    };
  }
}

export class UnauthorizedError extends AppError {
  readonly statusCode = 401;
  readonly code = "UNAUTHORIZED";
  constructor(message = "Authentication required") {
    super(message);
  }
}

export class ForbiddenError extends AppError {
  readonly statusCode = 403;
  readonly code = "FORBIDDEN";
  constructor(message = "izin ありません") {
    super(message);
  }
}

Result型pola

exception 使わず error type safety 扱うResult型pola.

> Result型pola implementasikan.
> berhasil dan gagal 型レベル dengan 区別 dengan きるよう 。
// types/result.ts
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 example
async function findUser(id: string): Promise<Result<User, NotFoundError>> {
  const user = await db.user.findUnique({ where: { id } });
  if (!user) {
    return err(new NotFoundError("User", id));
  }
  return ok(user);
}

// 呼び出し側
const result = await findUser("123");
if (result.success) {
  console.log(result.data.name); // type safety アクセス
} else {
  console.log(result.error.message); // error型 type safety
}

Global Error Handler

Express用 グローバルerrorhandler implementasi.

> Express グローバルerrorhandlermiddleware buatkan.
> AppError tepatなresponse konversi、予期しないerror 500 。
> environment produksi dengan スタックトレース 隠す。
import { Request, Response, NextFunction } from "express";
import { AppError } from "../errors/base";

export function globalErrorHandler(
  err: Error,
  req: Request,
  res: Response,
  _next: NextFunction
) {
  // ログoutput
  if (err instanceof AppError && err.isOperational) {
    console.warn(`[${err.code}] ${err.message}`);
  } else {
    console.error("Unexpected error:", err);
  }

  // AppError 場合 definisiされたresponse 返す
  if (err instanceof AppError) {
    return res.status(err.statusCode).json(err.toJSON());
  }

  // 予期し tidakerror
  res.status(500).json({
    error: {
      code: "INTERNAL_ERROR",
      message: process.env.NODE_ENV === "production"
        ? "servererror 発生しま"
        : err.message,
    },
  });
}

Menangkap Error Async

> Express async route handler error 
> 自動キャッチするラッパー buatkan.
import { Request, Response, NextFunction, RequestHandler } from "express";

function asyncHandler(
  fn: (req: Request, res: Response, next: NextFunction) => Promise<void>
): RequestHandler {
  return (req, res, next) => {
    fn(req, res, next).catch(next);
  };
}

// Usage example:try-catch 不要
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({ data: user });
}));

errorバウンダリ frontend

> React Error Boundary buatkan.
> error 種類 応じて異なるUI tampilkan.
import { Component, ReactNode } from "react";

interface Props {
  children: ReactNode;
  fallback?: (error: Error, retry: () => void) => ReactNode;
}

interface State {
  error: Error | null;
}

class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  handleRetry = () => {
    this.setState({ error: null });
  };

  render() {
    if (this.state.error) {
      if (this.props.fallback) {
        return this.props.fallback(this.state.error, this.handleRetry);
      }
      return (
        <div className="p-8 text-center">
          <h2 className="text-xl font-bold text-red-600">エラーが発生しました</h2>
          <p className="mt-2 text-gray-600">{this.state.error.message}</p>
          <button
            onClick={this.handleRetry}
            className="mt-4 rounded bg-blue-500 px-4 py-2 text-white"
          >
            再試行
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

debug dan error調査 spesifikなmetode debugテクニック完全panduan 、TypeScript 型設計 TypeScriptpengembangan pemanfaatan法 silakan lihat.セキュリティ 観点 dari error情報 扱い方 セキュリティ監査 otomatisasi juga あわせてご覧.

Summary

一貫 errorハンドリング設計 より、aplikasi robust性 dan maintainability 大幅 向上.Claude Code 使えば、カスタムerrorclass、Result型、グローバルhandler efisien implementasi bisa dilakukan.

Untuk errorハンドリングのbest practicesはNode.js公式panduan、Claude Code, lihat Anthropic公式ドキュメント.

#Claude Code #error handling #design patterns #TypeScript #robustness