Error Patterns
ในบท Intermediate เราเรียนเรื่อง Result และ ? ไปแล้ว
แต่ในโลกความจริงการจัดการ Error Type เองด้วยมือนั้นน่ารำคาญมาก!
นี่คือ pattern และ crates ที่ใช้กันในโลกจริงครับ
ลองนึกภาพว่า Error เป็นเหมือน “ข่าวสาร” ที่บอกว่าอะไรผิดพลาด เราต้องการให้ข่าวสารนี้ชัดเจน, มีบริบท, และง่ายต่อการ debug!
1. thiserror (สำหรับ Library)
Section titled “1. thiserror (สำหรับ Library)”1.1 Setup
Section titled “1.1 Setup”[dependencies]thiserror = "1"1.2 Custom Error Enum
Section titled “1.2 Custom Error Enum”use thiserror::Error;
// ============================================// #[derive(Error)] = สร้าง std::error::Error อัตโนมัติ// ============================================#[derive(Error, Debug)]pub enum AppError { // ============================================ // #[error("...")] = impl Display (ข้อความ error) // ============================================
// Static message #[error("File not found")] NotFound,
// Dynamic message ด้วย {0}, {1}, ... #[error("File not found: {0}")] FileNotFound(String),
// Named fields ด้วย {field_name} #[error("Invalid data in field '{field}': {value}")] InvalidData { field: String, value: String, },
// ============================================ // #[from] = implement From<T> อัตโนมัติ // ทำให้ ? แปลง error ให้เอง // ============================================ #[error("IO error: {0}")] Io(#[from] std::io::Error),
#[error("Parse error: {0}")] Parse(#[from] std::num::ParseIntError),}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google