// 定义错误类型模块
mod errors {
use serde::{Deserialize, Serialize};
// 基础错误类型
#[derive(Debug, Serialize, Deserialize)]
pub enum BaseError {
Other(String),
}
// 派生错误类型1
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorType1 {
pub msg: String,
}
impl From<ErrorType1> for BaseError {
fn from(e: ErrorType1) -> Self {
BaseError::Other(e.msg)
}
}
// 派生错误类型2
#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorType2 {
pub code: i32,
}
impl From<ErrorType2> for BaseError {
fn from(e: ErrorType2) -> Self {
BaseError::Other(format!("Error code: {}", e.code))
}
}
}
// 使用错误类型的模块
mod business_logic {
use super::errors::{BaseError, ErrorType1, ErrorType2};
use serde::{Deserialize, Serialize};
// 函数1,返回ErrorType1
pub fn function1() -> Result<(), ErrorType1> {
Err(ErrorType1 {
msg: "Function 1 error".to_string(),
})
}
// 函数2,返回ErrorType2
pub fn function2() -> Result<(), ErrorType2> {
Err(ErrorType2 { code: 42 })
}
// 函数3,传播错误
pub fn function3() -> Result<(), BaseError> {
function1().map_err(|e| e.into())?;
function2().map_err(|e| e.into())
}
}
fn main() {
use business_logic::{function1, function2, function3};
use errors::BaseError;
use serde_json;
// 处理function1的错误
match function1() {
Ok(_) => println!("Function 1 succeeded"),
Err(e) => println!("Function 1 failed: {:?}", e),
}
// 处理function2的错误
match function2() {
Ok(_) => println!("Function 2 succeeded"),
Err(e) => println!("Function 2 failed: {:?}", e),
}
// 处理function3的错误
match function3() {
Ok(_) => println!("Function 3 succeeded"),
Err(e) => println!("Function 3 failed: {:?}", e),
}
// 错误序列化
let error_type1 = ErrorType1 {
msg: "Serialized error".to_string(),
};
let serialized = serde_json::to_string(&error_type1).expect("Serialization failed");
println!("Serialized: {}", serialized);
// 错误反序列化
let deserialized: ErrorType1 = serde_json::from_str(&serialized).expect("Deserialization failed");
println!("Deserialized: {:?}", deserialized);
}
- 错误类型层次结构:在
errors
模块中定义了BaseError
作为基础错误类型,ErrorType1
和ErrorType2
作为派生错误类型,并实现了从派生类型到基础类型的转换。
- 函数返回不同错误类型:在
business_logic
模块中定义了function1
、function2
分别返回ErrorType1
和ErrorType2
,function3
则演示了错误的传播。
- 模块间共享错误类型:通过
mod
关键字定义模块,并使用use
关键字在不同模块间共享错误类型。
- 错误的序列化和反序列化:使用
serde
库及其Serialize
和Deserialize
trait 实现了错误类型的序列化和反序列化,示例中使用serde_json
进行JSON格式的序列化和反序列化。