设计思路
- 错误类型定义:定义统一的错误类型,将不同模块可能产生的错误统一起来,便于上层处理。
- 责任链模式:使用责任链模式,每个处理单元(模块)将错误传递给下一个处理单元,直到有处理单元能够处理该错误。
- 策略模式:可以为不同类型的错误定义不同的处理策略,在责任链的节点中根据错误类型选择合适的策略处理。
主要数据结构
- 错误类型定义:
#[derive(Debug)]
enum DistributedSystemError {
Module1Error(String),
Module2Error(String),
// 其他模块错误类型
}
- 责任链节点:
struct ErrorHandler {
next: Option<Box<ErrorHandler>>,
}
主要函数
- 错误处理函数:
impl ErrorHandler {
fn handle_error(&self, error: DistributedSystemError) {
if let Some(ref next) = self.next {
next.handle_error(error);
} else {
eprintln!("Unhandled error: {:?}", error);
}
}
}
- 添加下一个处理节点函数:
impl ErrorHandler {
fn set_next(&mut self, next: ErrorHandler) {
self.next = Some(Box::new(next));
}
}
关键代码片段
fn main() {
let mut handler1 = ErrorHandler { next: None };
let mut handler2 = ErrorHandler { next: None };
handler1.set_next(handler2);
let error = DistributedSystemError::Module1Error("Some error in module 1".to_string());
handler1.handle_error(error);
}
策略模式结合
- 定义错误处理策略 trait:
trait ErrorHandlingStrategy {
fn handle(&self, error: &DistributedSystemError);
}
- 不同策略实现:
struct Module1ErrorStrategy;
impl ErrorHandlingStrategy for Module1ErrorStrategy {
fn handle(&self, error: &DistributedSystemError) {
if let DistributedSystemError::Module1Error(_) = error {
println!("Handling Module1Error");
}
}
}
- 在责任链节点中使用策略:
struct ErrorHandler {
next: Option<Box<ErrorHandler>>,
strategy: Box<dyn ErrorHandlingStrategy>,
}
impl ErrorHandler {
fn handle_error(&self, error: DistributedSystemError) {
self.strategy.handle(&error);
if let Some(ref next) = self.next {
next.handle_error(error);
} else {
eprintln!("Unhandled error: {:?}", error);
}
}
}