0Pricing
Learn Rust Coding · Урок

thiserror

Пользовательские типы ошибок

«thiserror» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Custom Errors?

Libraries should expose meaningful error types so callers can react to specific failures. Writing these by hand means lots of boilerplate. The thiserror crate generates it for you.

Adding thiserror

Add it as a dependency. It is a derive-macro crate with zero runtime cost.

[dependencies]
thiserror = "1.0"

Defining an Error Enum

Derive Error on an enum where each variant is a distinct failure. The #[error("...")] attribute provides the Display message.

use thiserror::Error;

#[derive(Error, Debug)]
pub enum DataError {
    #[error("item not found")]
    NotFound,
    #[error("invalid input: {0}")]
    Invalid(String),
}

Interpolating Fields

The message string can reference named or positional fields, so error text carries context.

use thiserror::Error;

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("missing key: {key}")]
    Missing { key: String },
    #[error("value {0} out of range")]
    OutOfRange(i32),
}

Automatic Display and Error

The derive implements both Display (from your messages) and std::error::Error automatically. No manual impl blocks needed.

Wrapping a Source Error

#[from] generates a From impl so the ? operator can convert an underlying error into your type. #[source] marks the cause.

use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("io failure")]
    Io(#[from] std::io::Error),
    #[error("parse failure")]
    Parse(#[from] std::num::ParseIntError),
}

Using It with ?

Thanks to #[from], the ? operator auto-converts standard errors into your AppError.

fn read_number(path: &str) -> Result<i32, AppError> {
    let text = std::fs::read_to_string(path)?; // io::Error -> AppError
    let n: i32 = text.trim().parse()?;          // ParseIntError -> AppError
    Ok(n)
}

The source Chain

When you wrap an error, thiserror exposes the cause through Error::source, enabling full error chains for logging and debugging.

transparent Errors

#[error(transparent)] forwards both Display and source to the wrapped error, useful for a pass-through variant.

use thiserror::Error;

#[derive(Error, Debug)]
pub enum WrapError {
    #[error(transparent)]
    Other(#[from] std::io::Error),
}

When to Use thiserror

Reach for thiserror when:

  • You are writing a library
  • Callers need to match on specific error variants
  • You want a stable, typed error API

For applications where you just want to bubble errors up, anyhow is often simpler.

Matching on Variants

Because the error is a real enum, callers can match on it to react differently to each failure kind.

fn handle(err: AppError) {
    match err {
        AppError::Io(_) => println!("retry the file operation"),
        AppError::Parse(_) => println!("ask the user to fix input"),
    }
}

Quick Check

What does the #[from] attribute generate in a thiserror enum?

Recap

You learned the thiserror crate:

  • #[derive(Error)] generates Display and Error impls
  • #[error("...")] defines messages with field interpolation
  • #[from] enables ? conversion from source errors
  • transparent forwards to a wrapped error
  • Ideal for typed library error APIs

Часто задаваемые вопросы

Урок «thiserror» бесплатный?

Да — полный текст урока «thiserror» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.

Чему я научусь в уроке «thiserror»?

Пользовательские типы ошибок Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Learn Rust Coding?

Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «thiserror»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Learn Rust Coding?

Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Result и оператор ?
  2. thiserror
  3. anyhow
  4. Преобразование ошибок
← Назад к Learn Rust Coding