handle-errors-in-code
БесплатноБез исполняемых скриптовНе проверенWrite Rust error types: thiserror enums over anyhow, with context and actionable messages, and no source locations. Use when adding error types or handling a…
от torrust★ 539 звёзд на GitHubОб этом скилле
Handling Errors in Code
Core Principles
- Clarity — Users immediately understand what went wrong
- Context — Include what/where/when/why
- Actionability — Tell users how to fix it
- Explicit enums over
anyhow— Prefer structured errors for pattern matching
Prefer Explicit Enum Errors
// ✅ Correct: explicit, matchable, clear
#[derive(Debug, thiserror::Error)]
pub enum TrackerError {
#[error("Torrent '{info_hash}' not found in whitelist")]
TorrentNotWhitelisted { info_hash: InfoHash },
#[error("Peer limit exceeded for torrent '{info_hash}': max {limit}")]
PeerLimitExceeded { info_hash: InfoHash, limit: usize },
}
// ❌ Wrong: opaque, hard to match
return Err(anyhow::anyhow!("Something went wrong"));
return Err("Invalid input".into());
Include Actionable Fix Instructions in Display
When the error is user-facing, add instructions:
#[error(
"Configuration file not found at '{path}'.\n\
Copy the default: cp share/default/config/tracker.toml {path}"
)]
ConfigNotFound { path: PathBuf },
Context Requirements
Each error should answer:
- What: What operation was being performed?
- Where: Which component, file, or resource? (A runtime resource such as a config file or an address, not a source location.)
- When: Under what conditions?
- Why: What caused the failure?
// ✅ Good: full context
#[error("UDP socket bind failed for '{addr}': {source}. Is port {port} already in use?")]
SocketBindFailed { addr: SocketAddr, port: u16, source: std::io::Error },
// ❌ Bad: no context
return Err("bind failed".into());
No Source Locations in Errors
Errors must not record or print source locations. See ADR 20261118045443.
- No
locationfield and noLocation::caller()in error types. - No
torrust-located-error: keep a source error as a plain#[source](or#[from]) field. Displaystates what failed and the offending input, never a source path. A secret (an authentication key, a token, a password) is never echoed or kept in the error: name the parameter and the expected format instead (see thehandle-secretsskill).- Text sent to a client is chosen by the protocol layer from the class and the variant of the
error, not from its
Displaychain; see "Text Sent to a Client" below. Never format a source error from a crate the workspace does not control into client text. - For developer diagnostics, emit a
tracingevent at the site; it records file and line on the server only. #[track_caller]is allowed only in test helpers and assertion helpers.
// ✅ Correct: names what failed and the expected format, and does not keep the secret
#[derive(Debug, thiserror::Error)]
pub enum KeyError {
#[error("invalid authentication key: expected 32 alphanumeric characters, got {length}")]
InvalidKeyFormat { length: usize },
}
// ❌ Wrong: a location that reaches clients and logs
#[derive(Debug, thiserror::Error)]
pub enum KeyError {
#[error("invalid key format, {location}")]
InvalidKeyFormat { location: &'static Location<'static> },
}
Existing location fields and LocatedError uses are being removed by EPIC #2912; do not add new
ones.
Text Sent to a Client
What the HTTP tracker, the UDP tracker, the REST API and the health-check API tell a client when a request fails is decided by ADR 20261125175726, which amends rule 4 of the ADR above. Its tables list every current and proposed text; this is the rule to follow when you add or change a reply:
- Classify the failure first. A bad request (the client's own input) says what is wrong and
what is expected. A refusal (not whitelisted, key missing or expired, wrong token) says what was
refused and what the client can do. An internal failure (a database that is down, a state the code
did not expect) is the tracker's fault: one fixed sentence that names the operation and the request
id, for example
Internal tracker error: the announce could not be completed, try again later (request id: <id>), and nothing from the error or its source. - A cause the code can tell and the client caused is not an internal failure, even when a lower layer reports it as an error (a duplicate authentication key says so).
- One sentence, not the Rust error tree. The protocol layer builds the text from the variant
(
error_mapping.rsfor the HTTP tracker,Error::client_messagefor UDP, the response functions of the REST API, the probes of the health-check API). Never forwardDisplay,Debug, a type name, a database driver text, a library text (serde,axum,reqwest) or a server timing value. - Echo a client value only within the limits: at most 64 characters as sent, then
..., escaped with
Установить handle-errors-in-code в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл handle-errors-in-code?
Write Rust error types: thiserror enums over anyhow, with context and actionable messages, and no source locations. Use when adding error types or handling a Result.
Как установить скилл handle-errors-in-code?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл handle-errors-in-code запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic