Designing Error Boundaries with Claude Code: From Frontend to API
Designing Error Boundaries Claude Code का उपयोग करके. From Frontend to API. Includes practical code examples.
errorバウンダリ क्या है
errorバウンダリは、applicationの一部でerrorが発生しても全体がクラッシュしない तरहする防御的な設計pattern है।Claude Code का उपयोग करके、フロントエンドとバックエンドの両方で一貫したerrorprocessingを設計でき है।
React Error Boundary
import { Component, ErrorInfo, ReactNode } from "react";
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}
class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true, error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Error caught by boundary:", error, errorInfo);
this.props.onError?.(error, errorInfo);
// Send to error monitoring service
reportError(error, {
componentStack: errorInfo.componentStack,
});
}
render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div className="error-fallback">
<h2>errorが発生しました</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false, error: null })}>
再試行
</button>
</div>
)
);
}
return this.props.children;
}
}
functioncomponent向けhook
import { useCallback, useState } from "react";
function useErrorHandler() {
const [error, setError] = useState<Error | null>(null);
if (error) {
throw error; // 親のError Boundaryでキャッチ
}
const handleError = useCallback((err: unknown) => {
if (err instanceof Error) {
setError(err);
} else {
setError(new Error(String(err)));
}
}, []);
const withErrorHandling = useCallback(
<T,>(fn: () => Promise<T>) => {
return async () => {
try {
return await fn();
} catch (err) {
handleError(err);
return undefined;
}
};
},
[handleError]
);
return { handleError, withErrorHandling };
}
API errorresponseの標準化
// errorcode定義
enum ErrorCode {
VALIDATION_ERROR = "VALIDATION_ERROR",
NOT_FOUND = "NOT_FOUND",
UNAUTHORIZED = "UNAUTHORIZED",
FORBIDDEN = "FORBIDDEN",
CONFLICT = "CONFLICT",
INTERNAL_ERROR = "INTERNAL_ERROR",
RATE_LIMITED = "RATE_LIMITED",
}
interface ApiError {
code: ErrorCode;
message: string;
details?: Record<string, unknown>;
requestId: string;
timestamp: string;
}
class AppError extends Error {
constructor(
public code: ErrorCode,
message: string,
public statusCode: number,
public details?: Record<string, unknown>
) {
super(message);
this.name = "AppError";
}
static notFound(resource: string) {
return new AppError(
ErrorCode.NOT_FOUND,
`${resource} not found`,
404
);
}
static validation(details: Record<string, string>) {
return new AppError(
ErrorCode.VALIDATION_ERROR,
"Validation failed",
400,
details
);
}
static unauthorized(message = "Authentication required") {
return new AppError(ErrorCode.UNAUTHORIZED, message, 401);
}
}
グローバルerrorhandler
import { v4 as uuidv4 } from "uuid";
function globalErrorHandler(
err: Error,
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const requestId = uuidv4();
if (err instanceof AppError) {
// 業務error
return res.status(err.statusCode).json({
code: err.code,
message: err.message,
details: err.details,
requestId,
timestamp: new Date().toISOString(),
});
}
// 予期しないerror
console.error(`[${requestId}] Unexpected error:`, err);
res.status(500).json({
code: ErrorCode.INTERNAL_ERROR,
message: "An unexpected error occurred",
requestId,
timestamp: new Date().toISOString(),
});
}
// 登録順序がimportant:ルーターのबादに配置
app.use(globalErrorHandler);
asyncerrorのキャッチ
// asyncHandler wrapper
function asyncHandler(
fn: (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => Promise<void>
) {
return (
req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
// Usage example
router.get(
"/users/:id",
asyncHandler(async (req, res) => {
const user = await prisma.user.findUnique({
where: { id: req.params.id },
});
if (!user) {
throw AppError.notFound("User");
}
res.json({ data: user });
})
);
階層的errorバウンダリ
React側では複数のError Boundaryを階層的に配置し है।errorprocessingの設計をClaude Code को requestする際のreference के लिए देखें。プロンプトのलिखने का तरीकाは効果的なプロンプト5つのTips、code品質の改善にはrefactoringautomationも役立ち है।
function App() {
return (
<ErrorBoundary fallback={<FullPageError />}>
<Header />
<ErrorBoundary fallback={<SidebarFallback />}>
<Sidebar />
</ErrorBoundary>
<ErrorBoundary fallback={<ContentFallback />}>
<MainContent />
</ErrorBoundary>
</ErrorBoundary>
);
}
error handlingの設計原則के बारे मेंはMDN Web Docs: Error handlingが参考になり है।Claude Codeके details के लिएofficial documentation confirmして करें।
Summary
errorバウンダリはuser体験を損なわないためのimportantな設計pattern है।Claude Code का उपयोग करके、フロントエンド सेAPI तक一貫したerrorprocessingをefficientlyimplementationでき है।
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 करें।