error-handling
БесплатноБез исполняемых скриптовНе проверенError handling patterns across languages and layers — operational vs programmer errors, retry strategies, circuit breakers, error boundaries, HTTP responses…
от modbender★ 21 звезда на GitHubОб этом скилле
Error Handling Patterns
Ship resilient software. Handle errors at boundaries, fail fast and loud, never swallow exceptions silently.
Error Handling Philosophy
| Principle | Description |
|---|---|
| Fail Fast | Detect errors early — validate inputs at the boundary, not deep in business logic |
| Fail Loud | Errors must be visible — log them, surface them, alert on them |
| Handle at Boundaries | Catch and translate errors at layer boundaries (controller, middleware, gateway) |
| Let It Crash | For unrecoverable state, crash and restart (Erlang/OTP philosophy) |
| Be Specific | Catch specific error types, never bare catch or except |
| Provide Context | Every error carries enough context to diagnose without reproducing |
Error Types
Operational errors — network timeouts, invalid user input, file not found, DB connection lost. Handle gracefully.
Programmer errors — TypeError, null dereference, assertion failures. Fix the code — don't catch and suppress.
// Operational — handle gracefully
try {
const data = await fetch('/api/users');
} catch (err) {
if (err.code === 'ECONNREFUSED') return fallbackData;
throw err; // re-throw unexpected errors
}
// Programmer — let it crash, fix the bug
const user = null;
user.name; // TypeError — don't try/catch this
Language Patterns
| Language | Mechanism | Anti-Pattern |
|---|---|---|
| JavaScript | try/catch, Promise.catch, Error subclasses |
.catch(() => {}) swallowing errors |
| Python | Exceptions, context managers (with) |
Bare except: catching everything |
| Go | error returns, errors.Is/As, fmt.Errorf wrapping |
_ = riskyFunction() ignoring error |
| Rust | Result<T, E>, Option<T>, ? operator |
.unwrap() in production code |
JavaScript — Error Subclasses
class AppError extends Error {
constructor(message, code, statusCode, details = {}) {
super(message);
this.name = this.constructor.name;
this.code = code;
this.statusCode = statusCode;
this.details = details;
this.isOperational = true;
}
}
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} not found`, 'NOT_FOUND', 404, { resource, id });
}
}
class ValidationError extends AppError {
constructor(errors) {
super('Validation failed', 'VALIDATION_ERROR', 422, { errors });
}
}
Go — Error Wrapping
func GetUser(id string) (*User, error) {
row := db.QueryRow("SELECT * FROM users WHERE id = $1", id)
var user User
if err := row.Scan(&user.ID, &user.Name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
}
return nil, fmt.Errorf("querying user %s: %w", id, err)
}
return &user, nil
}
Error Boundaries
Express Error Middleware
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
const response = {
error: {
code: err.code || 'INTERNAL_ERROR',
message: err.isOperational ? err.message : 'Something went wrong',
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
requestId: req.id,
},
};
logger.error('Request failed', {
err, requestId: req.id, method: req.method, path: req.path,
});
res.status(statusCode).json(response);
});
React Error Boundary
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<h2>Something went wrong</h2>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => queryClient.clear()}>
<App />
</ErrorBoundary>
Retry Patterns
| Pattern | When to Use | Config |
|---|---|---|
| Exponential Backoff | Transient failures (network, 503) | Base 1s, max 30s, factor 2x |
| Backoff + Jitter | Multiple clients retrying | Random ±30% on each delay |
| Circuit Breaker | Downstream service failing repeatedly | Open after 5 failures, half-open after 30s |
| Bulkhead | Isolate failures to prevent cascade | Limit concurrent calls per service |
| Timeout | Prevent indefinite hangs | Connect 5s, read 30s, total 60s |
Exponential Backoff with Jitter
async function withRetry(fn, { maxRetries = 3, baseDelay = 1000, maxDelay = 30000 } = {}) {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt === maxRetries || !isRetryable(err)) throw err;
const delay = Math.min(baseDelay
Установить error-handling в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл error-handling?
Error handling patterns across languages and layers — operational vs programmer errors, retry strategies, circuit breakers, error boundaries, HTTP responses, graceful degradation, and structured logging. Use when designing error strategies, building resilient APIs, or reviewing error management.
Как установить скилл error-handling?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл error-handling запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic