</>
Plan du cours — 41/66

anyhow et thiserror — gestion d'erreurs

Intermédiaire
  • anyhow : erreurs d'application (binaires) — un type d'erreur universel avec du contexte.
  • thiserror : erreurs de bibliothèque — génère Display/Error/From pour vos enums.
cargo add anyhow thiserror
use anyhow::{Context, Result};
use thiserror::Error;

#[derive(Debug, Error)]
enum DbError {
    #[error("utilisateur {0} introuvable")]
    NotFound(u32),
    #[error("connexion impossible")]
    Connexion(#[from] std::io::Error),
}

fn lire_config() -> Result<String> {
    let contenu = std::fs::read_to_string("config.toml")
        .context("impossible de lire config.toml")?;
    Ok(contenu)
}