Error-Handling Rules
Libraries expose typed, actionable errors; applications aggregate context and report to users and logs. Panics are for bugs, not expected failures.
Busca en todas las páginas de la documentación
Libraries expose typed, actionable errors; applications aggregate context and report to users and logs. Panics are for bugs, not expected failures.
// library
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("not found: {0}")]
NotFound(UserId),
}
// application
fn main() -> anyhow::Result<()> {
run().context("app startup")?;
Ok(())
}When to reach for this: Any public API boundary and binary main.
| Layer | Type | Context |
|---|---|---|
| Domain | thiserror enum | precise variants |
| Adapter | map_err to domain | translate sqlx/reqwest |
| Handler | IntoResponse | status + problem JSON |
| main | anyhow::Result | human-readable chain |
pub fn load_config() -> Result<Config, ConfigError> { /* ... */ }
async fn handler() -> Result<Json<User>, ApiError> {
let user = repo.get(id).await?;
Ok(Json(user))
}What this demonstrates:
? propagates in same error type or From implunwrap user input paths.context("while X") at boundariessource() chain preserved for logs#[non_exhaustive] on public error enums for semver flexibilityanyhow only in binaries/integration tests, not published lib public APIError::source for chaining; avoid string-only errors in librariesResult<T, Error>.400 with message..map_err(|e| e.to_string()). Fix: #[from] or transparent variants.| Alternative | Use When | Don't Use When |
|---|---|---|
eyre | app error reports | Published library API |
| Panic | invariant violation | User typo in form |
Option | truly optional | operation can fail |
Common pattern; submodules use #[from] nested errors.
Wrap serde_json::Error in domain variant with context.
Implement IntoResponse on ApiError mapping variants to status.
RUST_BACKTRACE=1 in staging; anyhow optional backtrace feature.
Transient network/timeout only; not validation failures.
pub use Error from crate root; hide internal variants if needed with opaque type.
Match on ErrorKind or variant helpers, not Display strings.
core::fmt::Display manual impl; no anyhow.
Map domain errors to tonic Status in adapter layer.
Rustdoc # Errors on every fallible pub fn.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026