En bref. L’article sur ? a donné le contenant, Result<T, E>. Celui-ci s’occupe du E. Dans une bibliothèque, l’erreur est un enum avec une variante par cause, écrit avec thiserror : l’appelant peut décider. Dans l’application, elle devient un rapport, écrit avec anyhow et .context() : un humain peut comprendre. Deux #[from] du même type dans un enum donnent E0119, conflicting implementations of trait From<std::io::Error>.
Le modèle en une phrase
Une erreur de bibliothèque est une question posée à l’appelant : « lequel de ces cas ? ». Une erreur d’application est un rapport adressé à un humain : « voici ce que je faisais, et pourquoi ça a cassé ».
Le premier a besoin de tiroirs, un par cause. Le second a besoin d’une chaîne, un maillon par niveau.
In short. The article on ? gave us the container, Result<T, E>. This one deals with the E. In a library, the error is an enum with one variant per cause, written with thiserror: the caller can decide. In the application, it becomes a report, written with anyhow and .context(): a human can understand. Two #[from] of the same type in an enum give E0119, conflicting implementations of trait From<std::io::Error>.
The model in one sentence
A library error is a question for the caller: “which of these cases?”. An application error is a report for a human: “here’s what I was doing, and why it broke”.
The first needs drawers, one per cause. The second needs a chain, one link per level.
fn lire_port(chemin: &str) -> Result<u16, String> {let texte = fs::read_to_string(chemin).map_err(|e| e.to_string())?;texte.trim().parse::<u16>().map_err(|e| e.to_string())}
- Le raccourci :
Result<u16, String>etmap_err(|e| e.to_string()). Les deux causes finissent dans le même sac, en texte. L'appelant ne peut plus que lire une phrase.The shortcut:Result<u16, String>andmap_err(|e| e.to_string()). Both causes end up in the same bag, as text. The caller can only read a sentence. - Un
enumavecthiserror: une variante par cause.#[from]écrit leFrom, donc?range chaque erreur dans son tiroir.Anenumwiththiserror: one variant per cause.#[from]writes theFrom, so?files each error in its drawer. - On veut distinguer lire la configuration et écrire le cache, deux
io::Error. Deux#[from] io::Error: le?ne saurait pas quel tiroir choisir. E0119, conflicting implementations of trait `From<std::io::Error>`.We want to tell reading the config from writing the cache, twoio::Errors. Two#[from] io::Error:?wouldn't know which drawer to pick. E0119, conflicting implementations of trait `From<std::io::Error>`. - Le correctif : c'est le code qui choisit le tiroir, avec
map_err, et la variante garde le chemin. Un champ nommésourcedevient la cause. L'appelant peut réagir : fichier absent, port par défaut.The fix: the code picks the drawer, withmap_err, and the variant keeps the path. A field namedsourcebecomes the cause. The caller can react: missing file, default port.
Le raccourci String : un sac sans fond
fn lire_port(chemin: &str) -> Result<u16, String> {
let texte = fs::read_to_string(chemin).map_err(|e| e.to_string())?;
texte.trim().parse::<u16>().map_err(|e| e.to_string())
}Ça compile, ça s’affiche bien. Mais l’appelant qui veut un port par défaut quand le fichier manque n’a plus qu’une phrase, No such file or directory (os error 2), à comparer à la main. La cause a été convertie en texte trop tôt.
Bibliothèque : un tiroir par cause (thiserror)
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ErreurConfig {
#[error("lecture de {chemin}")]
Lecture { chemin: PathBuf, source: io::Error },
#[error("port invalide")]
Port(#[from] ParseIntError),
}
pub fn lire_port(chemin: &str) -> Result<u16, ErreurConfig> {
let texte = fs::read_to_string(chemin)
.map_err(|source| ErreurConfig::Lecture { chemin: chemin.into(), source })?;
let port = texte.trim().parse::<u16>()?;
Ok(port)
}thiserror n’est qu’une macro. Elle écrit ce que vous écririez à la main :
#[error("…")]devient l’implémentation deDisplay;#[derive(Error)]implémentestd::error::Error, et un champ nommésource(ou marqué#[from]) devient la cause renvoyée par.source();#[from]génèreimpl From<ParseIntError> for ErreurConfig, ce qui permet au?de convertir, exactement comme dans l’article précédent.
L’appelant ouvre le bon tiroir :
match lire_port(c) {
Ok(p) => println!("{c} : port {p}"),
Err(ErreurConfig::Lecture { chemin, .. }) =>
println!("{c} : fichier manquant, {} ; port par défaut 8080", chemin.display()),
Err(e) => {
let cause = std::error::Error::source(&e).map(|s| s.to_string()).unwrap_or_default();
println!("{c} : {e} ({cause})");
}
}absent.toml : fichier manquant, absent.toml ; port par défaut 8080
mauvais.txt : port invalide (invalid digit found in string)
bon.txt : port 8080Deux tiroirs pour la même étiquette : E0119
Pourquoi Lecture n’a-t-il pas de #[from] ? Parce qu’on voulait, à un moment, distinguer la lecture de la configuration et l’écriture d’un cache, deux io::Error :
#[derive(Debug, Error)]
pub enum ErreurConfig {
#[error("lecture de la configuration")]
Lecture(#[from] io::Error),
#[error("écriture du cache")]
Cache(#[from] io::Error),
}error[E0119]: conflicting implementations of trait `From<std::io::Error>` for type `ErreurConfig`
--> src/bin/conflit.rs:9:13
|
7 | Lecture(#[from] io::Error),
| ---- first implementation here
8 | #[error("écriture du cache")]
9 | Cache(#[from] io::Error),
| ^^^^ conflicting implementation for `ErreurConfig`Chaque #[from] écrit un impl From<io::Error> for ErreurConfig, et un type ne peut en avoir qu’un. Sur le fond, l’erreur est juste : face à une io::Error, le ? n’aurait aucun moyen de savoir s’il s’agit de la configuration ou du cache. C’est le code qui le sait, au moment de l’appel. D’où le correctif ci-dessus : pas de #[from], un map_err qui choisit la variante, et un champ (chemin) qui garde ce que l’io::Error ne dit pas.
Application : un maillon par niveau (anyhow)
Au sommet de la pile, dans main, personne ne fera de match : il faut afficher quelque chose d’utile et sortir. anyhow::Result<T> accepte n’importe quelle erreur. Sans précaution, le rapport est maigre :
fn main() -> anyhow::Result<()> {
let _texte = fs::read_to_string("absent.toml")?;
Ok(())
}Error: No such file or directory (os error 2)Quel fichier ? .context() et .with_context() ajoutent ce qu’on faisait :
use anyhow::{Context, Result};
fn lire_port(chemin: &str) -> Result<u16> {
let texte = fs::read_to_string(chemin)
.with_context(|| format!("lecture de {chemin}"))?;
let port = texte.trim().parse::<u16>()
.with_context(|| format!("port invalide dans {chemin} : {:?}", texte.trim()))?;
Ok(port)
}
fn main() -> Result<()> {
let chemin = std::env::args().nth(1).unwrap_or("absent.toml".into());
let port = lire_port(&chemin).context("démarrage du serveur")?;
println!("port {port}");
Ok(())
}Error: démarrage du serveur
Caused by:
0: lecture de absent.toml
1: No such file or directory (os error 2)Et avec mauvais.txt :
Error: démarrage du serveur
Caused by:
0: port invalide dans mauvais.txt : "80a"
1: invalid digit found in stringLe rapport se lit de haut en bas, de l’intention à la cause. Le code de sortie est 1.
Les deux ensemble
La bibliothèque garde son enum ; le binaire le reçoit dans anyhow sans rien perdre, parce qu’ErreurConfig implémente Error et expose sa source :
fn main() -> anyhow::Result<()> {
let port = lire_port(&chemin).context("démarrage du serveur")?;
// …
}Error: démarrage du serveur
Caused by:
0: lecture de absent.toml
1: No such file or directory (os error 2)La ligne lecture de absent.toml vient du #[error("lecture de {chemin}")] de la bibliothèque, la dernière de sa source.
Ce que l’image cache
- La cause affichée deux fois. Avec
#[error("lecture impossible : {0}")]sur un#[from] io::Error, anyhow affiche Error: lecture impossible : No such file or directory (os error 2), puis la même cause sous Caused by. Le message dit ce qu’on faisait ; la source dit pourquoi ça a cassé. On ne mélange pas. - anyhow dans une bibliothèque, c’est une boîte opaque. L’appelant peut encore s’en sortir avec
e.downcast_ref::<io::Error>()(iciSome(NotFound)), mais rien dans la signature ne lui garantit quel type est caché dedans. - Un enum public est un contrat. Ajouter une variante casse les
matchexhaustifs de vos utilisateurs (E0004).#[non_exhaustive]sur l’enum les oblige à prévoir un bras_. - Toutes les conditions ne méritent pas un
Result. Un fichier absent est une erreur attendue. Un index qui ne devrait jamais être hors limites est un bug : c’est le sujet du prochain numéro,panicet invariants.
Pour aller plus loin
- Volume 4, numéro 02 de The Rust Loop, Concevoir ses erreurs : thiserror vs anyhow, avec le contre-exemple d’anyhow dans une bibliothèque et trois cas de terrain (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277). - Documentation de thiserror
- Documentation d’anyhow
- Index des erreurs : E0119
The String shortcut: a bottomless bag
fn lire_port(chemin: &str) -> Result<u16, String> {
let texte = fs::read_to_string(chemin).map_err(|e| e.to_string())?;
texte.trim().parse::<u16>().map_err(|e| e.to_string())
}It compiles, it prints nicely. But a caller who wants a default port when the file is missing only has a sentence, No such file or directory (os error 2), to compare by hand. The cause was turned into text too early.
Library: one drawer per cause (thiserror)
ErreurConfig means “config error”; its variants are Lecture (“read”) and Port.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ErreurConfig {
#[error("lecture de {chemin}")]
Lecture { chemin: PathBuf, source: io::Error },
#[error("port invalide")]
Port(#[from] ParseIntError),
}
pub fn lire_port(chemin: &str) -> Result<u16, ErreurConfig> {
let texte = fs::read_to_string(chemin)
.map_err(|source| ErreurConfig::Lecture { chemin: chemin.into(), source })?;
let port = texte.trim().parse::<u16>()?;
Ok(port)
}thiserror is just a macro. It writes what you would write by hand:
#[error("…")]becomes theDisplayimplementation;#[derive(Error)]implementsstd::error::Error, and a field namedsource(or marked#[from]) becomes the cause returned by.source();#[from]generatesimpl From<ParseIntError> for ErreurConfig, which lets?convert, exactly as in the previous article.
The caller opens the right drawer:
match lire_port(c) {
Ok(p) => println!("{c} : port {p}"),
Err(ErreurConfig::Lecture { chemin, .. }) =>
println!("{c} : fichier manquant, {} ; port par défaut 8080", chemin.display()),
Err(e) => {
let cause = std::error::Error::source(&e).map(|s| s.to_string()).unwrap_or_default();
println!("{c} : {e} ({cause})");
}
}absent.toml : fichier manquant, absent.toml ; port par défaut 8080
mauvais.txt : port invalide (invalid digit found in string)
bon.txt : port 8080(“fichier manquant … port par défaut”: missing file, default port.)
Two drawers for the same label: E0119
Why doesn’t Lecture have a #[from]? Because at some point we wanted to tell reading the config apart from writing a cache (Cache), two io::Errors:
#[derive(Debug, Error)]
pub enum ErreurConfig {
#[error("lecture de la configuration")]
Lecture(#[from] io::Error),
#[error("écriture du cache")]
Cache(#[from] io::Error),
}error[E0119]: conflicting implementations of trait `From<std::io::Error>` for type `ErreurConfig`
--> src/bin/conflit.rs:9:13
|
7 | Lecture(#[from] io::Error),
| ---- first implementation here
8 | #[error("écriture du cache")]
9 | Cache(#[from] io::Error),
| ^^^^ conflicting implementation for `ErreurConfig`Each #[from] writes an impl From<io::Error> for ErreurConfig, and a type can only have one. And the error is right on substance: faced with an io::Error, ? would have no way of knowing whether it’s about the config or the cache. The code knows, at the call site. Hence the fix above: no #[from], a map_err that picks the variant, and a field (chemin, the path) that keeps what the io::Error doesn’t say.
Application: one link per level (anyhow)
At the top of the stack, in main, nobody will match: you need to print something useful and exit. anyhow::Result<T> accepts any error. Without care, the report is thin:
fn main() -> anyhow::Result<()> {
let _texte = fs::read_to_string("absent.toml")?;
Ok(())
}Error: No such file or directory (os error 2)Which file? .context() and .with_context() add what you were doing:
use anyhow::{Context, Result};
fn lire_port(chemin: &str) -> Result<u16> {
let texte = fs::read_to_string(chemin)
.with_context(|| format!("lecture de {chemin}"))?;
let port = texte.trim().parse::<u16>()
.with_context(|| format!("port invalide dans {chemin} : {:?}", texte.trim()))?;
Ok(port)
}
fn main() -> Result<()> {
let chemin = std::env::args().nth(1).unwrap_or("absent.toml".into());
let port = lire_port(&chemin).context("démarrage du serveur")?;
println!("port {port}");
Ok(())
}Error: démarrage du serveur
Caused by:
0: lecture de absent.toml
1: No such file or directory (os error 2)And with mauvais.txt (“bad.txt”):
Error: démarrage du serveur
Caused by:
0: port invalide dans mauvais.txt : "80a"
1: invalid digit found in stringThe report reads top to bottom, from intent (“démarrage du serveur”, server startup) to cause. The exit code is 1.
Both together
The library keeps its enum; the binary receives it in anyhow without losing anything, because ErreurConfig implements Error and exposes its source:
fn main() -> anyhow::Result<()> {
let port = lire_port(&chemin).context("démarrage du serveur")?;
// …
}Error: démarrage du serveur
Caused by:
0: lecture de absent.toml
1: No such file or directory (os error 2)The line lecture de absent.toml comes from the library’s #[error("lecture de {chemin}")], the last one from its source.
What the picture hides
- The cause printed twice. With
#[error("lecture impossible : {0}")]on a#[from] io::Error, anyhow prints Error: lecture impossible : No such file or directory (os error 2), then the same cause under Caused by. The message says what you were doing; the source says why it broke. Don’t mix them. - anyhow in a library is an opaque box. The caller can still cope with
e.downcast_ref::<io::Error>()(hereSome(NotFound)), but nothing in the signature guarantees which type is hidden inside. - A public enum is a contract. Adding a variant breaks your users’ exhaustive
matches (E0004).#[non_exhaustive]on the enum makes them plan for a_arm. - Not every condition deserves a
Result. A missing file is an expected error. An index that should never be out of bounds is a bug: that’s the topic of the next issue,panicand invariants.
Going further
- Volume 4, issue 02 of The Rust Loop, Designing your errors: thiserror vs anyhow, with the counter-example of anyhow in a library and three field cases (link at the bottom of the page).
- Previous articles: the move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277). - thiserror documentation
- anyhow documentation
- Error index: E0119