thiserror ou anyhow ? Concevoir ses erreurs en Rust, et E0119 « conflicting implementations of trait From » thiserror or anyhow? Designing your errors in Rust, and E0119 "conflicting implementations of trait From"

Une erreur de bibliothèque est une question posée à l'appelant : un enum, une variante par cause (thiserror). Une erreur d'application est un rapport pour un humain : une chaîne de contexte (anyhow). Deux #[from] du même type donnent E0119. Animation et sorties réelles.A library error is a question for the caller: an enum, one variant per cause (thiserror). An application error is a report for a human: a chain of context (anyhow). Two #[from] of the same type give E0119. Animation and real output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ErreursErrors
PubliéPublished

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())
}
Qui lit l'erreurWho reads the errorthiserror : un type que l'appelant filtrethiserror: a type the caller can matchResult<u16, String>io::ErrorParseIntError"No such file or…"appelantcallerlit du textereads textet devineand guessesune phrase : impossible de décider sans comparer du textea sentence: no way to decide without comparing textvérifié avec rustc 1.100checked with rustc 1.100
  1. Le raccourci : Result<u16, String> et map_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> and map_err(|e| e.to_string()). Both causes end up in the same bag, as text. The caller can only read a sentence.
  2. Un enum avec thiserror : une variante par cause. #[from] écrit le From, donc ? range chaque erreur dans son tiroir.An enum with thiserror: one variant per cause. #[from] writes the From, so ? files each error in its drawer.
  3. 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, two io::Errors. Two #[from] io::Error: ? wouldn't know which drawer to pick. E0119, conflicting implementations of trait `From<std::io::Error>`.
  4. Le correctif : c'est le code qui choisit le tiroir, avec map_err, et la variante garde le chemin. Un champ nommé source devient la cause. L'appelant peut réagir : fichier absent, port par défaut.The fix: the code picks the drawer, with map_err, and the variant keeps the path. A field named source becomes the cause. The caller can react: missing file, default port.
Erreurs de bibliothèque en Rust : avec thiserror, un enum avec une variante par cause, et #[from] pour que ? convertisse. Deux #[from] du même type donnent E0119.Library errors in Rust: with thiserror, an enum with one variant per cause, and #[from] so ? converts. Two #[from] of the same type give E0119.

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 de Display ;
  • #[derive(Error)] implémente std::error::Error, et un champ nommé source (ou marqué #[from]) devient la cause renvoyée par .source() ;
  • #[from] génère impl 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 8080

Deux 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 string

Le 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>() (ici Some(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 match exhaustifs 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, panic et invariants.

Pour aller plus loin

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 the Display implementation;
  • #[derive(Error)] implements std::error::Error, and a field named source (or marked #[from]) becomes the cause returned by .source();
  • #[from] generates impl 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.

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 string

The 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>() (here Some(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, panic and invariants.

Going further

Questions fréquentesFrequently asked questions

thiserror ou anyhow : lequel choisir ?thiserror or anyhow: which one should I pick?

Les deux, à deux endroits différents. Dans une bibliothèque, thiserror : un enum public avec une variante par cause, que l'appelant peut traiter avec un match. Dans le binaire, au sommet de la pile, anyhow : un seul type qui accepte toute erreur, et .context() pour écrire un rapport lisible.Both, in two different places. In a library, thiserror: a public enum with one variant per cause, which the caller can handle with a match. In the binary, at the top of the stack, anyhow: a single type that accepts any error, and .context() to write a readable report.

Pourquoi E0119 « conflicting implementations of trait `From<std::io::Error>` » avec thiserror ?Why E0119 "conflicting implementations of trait `From<std::io::Error>`" with thiserror?

Deux variantes du même enum portent #[from] io::Error. #[from] génère un impl From<io::Error>, et il ne peut y en avoir qu'un : le ? ne saurait pas quelle variante choisir. Retirez #[from] et choisissez la variante dans le code avec map_err, en y ajoutant ce qui distingue les deux cas (le chemin, par exemple).Two variants of the same enum carry #[from] io::Error. #[from] generates an impl From<io::Error>, and there can be only one: ? wouldn't know which variant to choose. Drop #[from] and pick the variant in code with map_err, adding what tells the two cases apart (the path, for instance).

Pourquoi mon erreur s'affiche-t-elle deux fois avec anyhow ?Why is my error printed twice with anyhow?

Le message de la variante recopie sa cause, par exemple #[error("lecture impossible : {0}")] sur un #[from] io::Error. anyhow affiche le message, puis la source sous « Caused by » : la même phrase sort deux fois. Le message doit dire ce qu'on faisait, pas répéter la source.The variant's message copies its cause, for example #[error("lecture impossible : {0}")] on a #[from] io::Error. anyhow prints the message, then the source under "Caused by": the same sentence comes out twice. The message should say what you were doing, not repeat the source.

Pourquoi ne pas renvoyer Result<T, String> ?Why not return Result<T, String>?

Parce que la cause devient une phrase. L'appelant ne peut plus distinguer un fichier absent d'un port invalide qu'en comparant du texte, qui change au premier reformulage. Un enum garde la cause sous forme de type jusqu'à l'endroit où l'on décide quoi faire.Because the cause becomes a sentence. The caller can only tell a missing file from an invalid port by comparing text, which changes at the first rewording. An enum keeps the cause as a type up to the place where you decide what to do.

Peut-on utiliser anyhow dans une bibliothèque ?Can I use anyhow in a library?

On peut, mais l'appelant reçoit alors une boîte opaque. Pour savoir si le fichier manquait, il doit deviner le type caché et appeler downcast_ref::<io::Error>(), sans que la signature le garantisse. anyhow convient au binaire ; une bibliothèque publique expose un enum.You can, but the caller then gets an opaque box. To know whether the file was missing, it has to guess the hidden type and call downcast_ref::<io::Error>(), with no guarantee from the signature. anyhow suits the binary; a public library exposes an enum.

RustthiserroranyhowE0119Gestion d'erreursModèle mental

← Tous les articlesAll articles