liveBook · Manning

Thiserror

As explained in Learn Rust in a Month of Lunches

thiserror is a Rust library crate that provides derive macros for defining custom error types with standard error-trait implementations.

thiserror is a Rust library crate for defining custom error types with less repetitive code. Its main convenience is the derive macro thiserror::Error, which implements std::error::Error for your type. section 17.5 section 17.5.2

A typical custom error enum uses attributes to describe messages and conversions:

  • Add #[derive(Error, Debug)] to the enum. section 17.5.2
  • Put #[error("...")] above each variant to generate its Display message; the format follows format! syntax. section 17.5.2
  • Put #[from] on an error field to generate a From implementation, allowing the ? operator to convert that error into the custom enum. section 17.5.2
  • Use the custom enum when a library needs a proper, discoverable error type rather than only one general-purpose error value. section 17.5 section 17.8

One error type for several failures

An enum can represent sending, UTF-8, parsing, color, and other failures. With #[from] on Utf8Error and ParseIntError, parse_then_send can use ? while still returning Result<(), SystemError>. Display produces messages such as “Couldn't turn into an i32: invalid digit found in string”; Debug does not show these added messages.

#[derive(Error, Debug)]                                   #1
 
enum SystemError {
    #[error("Couldn't send: {0}")]                        #2
 
    SendError(String),
    #[error("Couldn't parse into a str: {0}")]            #3
 
    StringFromUtf8Error(#[from] Utf8Error),
    #[error("Couldn't turn into an i32: {0}")]
    ParseI32Error(#[from] ParseIntError),
    #[error("Wrong color: Red {0} Green {1} Blue {2}")]   #4
 
    ColorError(u8, u8, u8),
    #[error("Something happened")]
    OtherError,
}

Inspect the annotated SystemError enum to see how derive, error messages, source error fields, and numeric formatting fit together. section 17.5.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains derives, Display messages, From conversions, and a complete parsing example, then defers blanket implementations.
Examples
Uses a SystemError enum, parsing and sending functions, conversion attributes, formatted messages, and representative failure output.
What it assumes
Assumes basic Rust error handling and introduces the decision between unwrap, anyhow, and custom error types.
What you can do after
Build custom Rust error enums with generated trait implementations, formatted messages, and automatic conversions from underlying errors.
How it connects
Connects custom error types with std::error::Error, Display, From, Result, the ? operator, and anyhow.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.