Claude Code के साथ Error Handling Design Patterns
Claude Code का उपयोग करके error handling design patterns सीखें। Practical tips और code examples शामिल हैं।
error handlingの設計को Claude Code से改善する
appropriateなerror handlingはapplicationのrobust性に直結し है।Claude Code का उपयोग करके、型safeで一貫性のあるerror handlingpatternをefficientlyimplementationでき है।
カスタムerrorclassの設計
> application全体でuse करनाカスタムerrorclassを設計して。
> HTTPステータスcodeとのsupport、errorcode、
> user向けmessageを含めて。
// 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("validationerrorがあります");
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 = "権限がありません") {
super(message);
}
}
Result型pattern
例बाहरを使わずにerrorを型safeに扱うResult型pattern है।
> Result型patternをimplement करो。
> 成功と失敗を型レベルで区別できる तरह。
// 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); // 型safeにアクセス
} else {
console.log(result.error.message); // error型も型safe
}
グローバルerrorhandler
Express用のグローバルerrorhandlerをimplement करते हैं。
> Expressのグローバルerrorhandlermiddlewareをबनाओ。
> AppErrorはappropriateなresponseに変換、予期しないerrorは500に。
> 本番環境ではスタックトレースを隠す。
import { Request, Response, NextFunction } from "express";
import { AppError } from "../errors/base";
export function globalErrorHandler(
err: Error,
req: Request,
res: Response,
_next: NextFunction
) {
// log出力
if (err instanceof AppError && err.isOperational) {
console.warn(`[${err.code}] ${err.message}`);
} else {
console.error("Unexpected error:", err);
}
// AppError के case मेंは定義されたresponseを返す
if (err instanceof AppError) {
return res.status(err.statusCode).json(err.toJSON());
}
// 予期しないerror
res.status(500).json({
error: {
code: "INTERNAL_ERROR",
message: process.env.NODE_ENV === "production"
? "servererrorが発生しました"
: err.message,
},
});
}
asyncerrorのキャッチ
> Express のasync route handlerのerrorを
> 自動キャッチするwrapperをबनाओ。
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バウンダリ
> React Error Boundary をबनाओ。
> errorの種類に応じて異なるUI displayして。
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">errorが発生しました</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とerror調査の具体的な方法はdebugテクニックcomplete guideを、TypeScriptでの型設計はTypeScriptdevelopmentでのutilization法をदेखें。securityの観点 सेのerror情報の扱い方はsecurity監査のautomationもあわせてदेखें。
Summary
一貫したerror handling設計 से、applicationのrobust性と保守性が大幅に向ऊपरし है।Claude Code का उपयोग करके、カスタムerrorclass、Result型、グローバルhandlerをefficientlyimplementationでき है।
error handlingのベストプラクティスはNode.js公式ガイド、Claude Codeके बारे मेंはAnthropicofficial documentationをदेखें。
Related Posts
Claude Code Hooks में Mastery: Auto-Format, Auto-Test, और बहुत कुछ
Claude Code hooks से auto-formatting और auto-testing setup करना सीखें। Practical configuration examples और real-world use cases शामिल हैं।
Claude Code MCP Server Setup और Practical Use Cases
Claude Code की MCP server capabilities की comprehensive guide। External tools connect करना, servers configure करना, और real-world integration examples सीखें।
CLAUDE.md लिखने की Complete Guide: Project Configuration की Best Practices
Effective CLAUDE.md files लिखने की thorough guide। अपना tech stack, conventions, और project structure communicate करना सीखें और Claude Code की output quality maximize करें।