Rust 自定义错误类型
示例
use std::error::Error;
use std::fmt;
use std::convert::From;
use std::io::Error as IoError;
use std::str::Utf8Error;
#[derive(Debug)] // Allow the use of "{:?}" format specifier
enum CustomError {
Io(IoError),
Utf8(Utf8Error),
Other,
}
// Allow the use of "{}" format specifier
impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CustomError::Io(ref cause) => write!(f, "I/O Error: {}", cause),
CustomError::Utf8(ref cause) => write!(f, "UTF-8 Error: {}", cause),
CustomError::Other => write!(f, "未知错误!"),
}
}
}
//允许将此类型视为错误
impl Error for CustomError {
fn description(&self) -> &str {
match *self {
CustomError::Io(ref cause) => cause.description(),
CustomError::Utf8(ref cause) => cause.description(),
CustomError::Other => "未知错误!",
}
}
fn cause(&self) -> Option<&Error> {
match *self {
CustomError::Io(ref cause) => Some(cause),
CustomError::Utf8(ref cause) => Some(cause),
CustomError::Other => None,
}
}
}
//支持将系统错误转换为我们的自定义错误。
//该特征在“try!”中使用。
impl From<IoError> for CustomError {
fn from(cause: IoError) -> CustomError {
CustomError::Io(cause)
}
}
impl From<Utf8Error> for CustomError {
fn from(cause: Utf8Error) -> CustomError {
CustomError::Utf8(cause)
}
}
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法