Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от torrust★ 539 звёзд на GitHub

Об этом скилле

Handling Errors in Code

Core Principles

  1. Clarity — Users immediately understand what went wrong
  2. Context — Include what/where/when/why
  3. Actionability — Tell users how to fix it
  4. 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 location field and no Location::caller() in error types.
  • No torrust-located-error: keep a source error as a plain #[source] (or #[from]) field.
  • Display states 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 the handle-secrets skill).
  • Text sent to a client is chosen by the protocol layer from the class and the variant of the error, not from its Display chain; 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 tracing event 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.rs for the HTTP tracker, Error::client_message for UDP, the response functions of the REST API, the probes of the health-check API). Never forward Display, 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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить handle-errors-in-code с