在Rust中,你可以通過實現std::error::Error
和std::fmt::Display
trait來創建自定義錯誤類型。下面是一個簡單的例子:
use std::fmt;
use std::error;
// 定義一個自定義錯誤類型
#[derive(Debug)]
pub enum CustomError {
IoError(std::io::Error),
ParseError(std::num::ParseIntError),
OtherError(String),
}
// 實現From trait,以便可以從標準錯誤中轉換
impl From<std::io::Error> for CustomError {
fn from(err: std::io::Error) -> CustomError {
CustomError::IoError(err)
}
}
impl From<std::num::ParseIntError> for CustomError {
fn from(err: std::num::ParseIntError) -> CustomError {
CustomError::ParseError(err)
}
}
// 實現Error trait
impl error::Error for CustomError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
CustomError::IoError(ref err) => Some(err),
CustomError::ParseError(ref err) => Some(err),
CustomError::OtherError(ref _msg) => None,
}
}
}
// 實現Display trait
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CustomError::IoError(ref err) => write!(f, "IO error: {}", err),
CustomError::ParseError(ref err) => write!(f, "Parse error: {}", err),
CustomError::OtherError(ref msg) => write!(f, "Other error: {}", msg),
}
}
}
// 示例函數,返回自定義錯誤
fn parse_number(s: &str) -> Result<i32, CustomError> {
s.parse::<i32>().map_err(CustomError::from)
}
fn main() {
match parse_number("123") {
Ok(num) => println!("Parsed number: {}", num),
Err(e) => println!("Error: {}", e),
}
}
在這個例子中,我們定義了一個名為CustomError
的枚舉類型,它包含了三種可能的錯誤:IoError
、ParseError
和OtherError
。我們還實現了From
trait,以便可以從標準錯誤中轉換到自定義錯誤。最后,我們實現了Error
和Display
trait,以便可以方便地使用和顯示自定義錯誤。