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 errorstransparentforwards 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 يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- Result والمعامل ?
- thiserror
- anyhow
- تحويل الأخطاء