Error Structs
Error types ใน Rust standard library และ patterns สำหรับ custom error types - พื้นฐานสำคัญสำหรับการจัดการ errors อย่างเป็นระบบ
std::io::Error
Section titled “std::io::Error”std::io::Error เป็น error type หลักของ I/O operations มี ErrorKind สำหรับจัดหมวดหมู่ errors และสามารถเก็บ underlying OS error code ได้
io::Error Methods
Section titled “io::Error Methods”| Method | Parameters | Returns | Description |
|---|---|---|---|
Error::new(kind, error) | kind: ErrorKind, error: impl Into<Box<dyn Error>> | Error | สร้าง error ใหม่ |
Error::from_raw_os_error(code) | code: i32 | Error | สร้างจาก OS error code |
Error::last_os_error() | - | Error | Get last OS error |
.kind() | - | ErrorKind | Get error category |
.raw_os_error() | - | Option<i32> | Get OS error code |
.get_ref() | - | Option<&(dyn Error + Send + Sync)> | Get inner error reference |
.get_mut() | - | Option<&mut (dyn Error + Send + Sync)> | Get mutable inner error |
.into_inner() | - | Option<Box<dyn Error + Send + Sync>> | Take inner error |
Creating and Inspecting IO Errors
Section titled “Creating and Inspecting IO Errors”use std::io::{self, ErrorKind};
fn main() { // Create errors with ErrorKind and message let not_found = io::Error::new(ErrorKind::NotFound, "file not found"); let custom = io::Error::new(ErrorKind::Other, "custom error message");
println!("=== Error Display ==="); println!("NotFound: {}", not_found); println!("Custom: {}", custom);
// Error kind - useful for matching println!("\n=== Error Kind ==="); println!("not_found.kind(): {:?}", not_found.kind());
// Match on kind for structured handling match not_found.kind() { ErrorKind::NotFound => println!("File not found!"), ErrorKind::PermissionDenied => println!("Permission denied!"), ErrorKind::ConnectionRefused => println!("Connection refused!"), ErrorKind::TimedOut => println!("Operation timed out!"), ErrorKind::InvalidInput => println!("Invalid input!"), ErrorKind::InvalidData => println!("Invalid data!"), ErrorKind::Interrupted => println!("Operation interrupted!"), _ => println!("Other error"), }
// From OS error code (platform-specific) let os_error = io::Error::from_raw_os_error(2); // ENOENT on Unix println!("\n=== OS Error ==="); println!("OS error 2: {}", os_error); if let Some(code) = os_error.raw_os_error() { println!("Raw code: {}", code); }
// Last OS error - useful after syscalls // let last = io::Error::last_os_error();
// Get inner error if exists println!("\n=== Inner Error ==="); if let Some(inner) = custom.get_ref() { println!("Inner type: {:?}", inner); }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google