Rust-高级-Crate之error_chain

  1. 基础
  2. 原生操作
    1. 自定义错误
    2. 第三方错误转换
    3. 使用
  3. Error-chain操作
  4. 避免在错误转变过程中遗漏错误
  5. 获取复杂错误场景的回溯
  6. 具体内容可以展开宏

基础

error-chain 可以轻松地充分利用 Rust 的错误处理功能,而无需维护样板错误类型和转换的开销。它实现了一种自以为是的策略来定义您自己的错误类型,以及从其他错误类型的转换。

原生操作

错误处理编程三步骤:

  1. 定义自己的错误类型
  2. 实现错误提示函数
  3. 关联外部错误类型

自定义错误

首先,实现我们的自定义类型。

use std::{io, fmt};

/// 第一步,自定义错误类型
#[derive(Debug)]
enum MyError {
Single,
Duple(String),
Multi(u32, Vec<u32>),
IO(io::Error),
}

/// 第二步,实现打印函数
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self {
MyError::Single => write!(f, "Single Error"),
MyError::Duple(ref err) => write!(f, "Dutple {} Error", err),
MyError::Multi(ref len, ref data) => write!(f, "Multi len {} data {:?} Error", len, data),
MyError::IO(ref e) => write!(f, "IO: {}", e)
}
}
}

/// 错误通用化
impl std::error::Error for MyError {
fn description(&self) -> &str {
"MyError"
}

fn cause(&self) -> Option<&dyn std::error::Error> {
None
}
}

第三方错误转换

实现上面两步,我们可以返回错误,并显示错误信息。当然,我们不能仅限于此,当我使用系统库或者第三方库时,通常会有其他错误类型,需要转换成MyError类型方便管理。

/// 第三步,实现其他错误类型转换
impl From<io::Error> for MyError {
fn from(error: io::Error) -> Self {
MyError::IO(error)
}
}

使用

完成上述三步,我们可以轻松处理错误了。 当我们读取不存在的文件返回了一个io错误,把它转换成MyError类型。

fn read() -> std::result::Result<(), MyError> {
let _file = File::open("unknown_file.txt")?;
std::result::Result::Ok(())
}

fn main() {
match read() {
std::result::Result::Ok(_) => println!("No Error"),
std::result::Result::Err(e) => println!("{}", e),
}
}

打印出带IO的错误:

IO:No such file or directory (os error 2)

Error-chain操作

error-chain!宏,帮我们让代码更加简洁。
帮我们实现了Error结构体,ErrorKind枚举,ResultExt结构体,Result别名。

error_chain! {
foreign_links {
Io(::std::io::Error) #[doc = "Error during IO"];
}
errors {
Single {
description("MyError!")
display("Single Error")
}
Duple(t: String) {
description("MyError!")
display("Dutple {} Error", t)
}
Multi(len: u32, data: Vec<u32>) {
description("MyError!")
display("Multi len {} data {:?} Error", len, data)
}
}
}

当然,上面并不是库的全部用法。
看看下面的demo:
pub mod other_crate{
use error_chain::*;
error_chain! {
errors{

}
}
}

pub mod main_crate{
use error_chain::*;
use crate::other_crate;
error_chain!{
// 为此错误定义的类型。这些是常规的和推荐的名称,但可以任意选择。也可以完全忽略此部分,或者将其留空,这些名称将被自动使用。
types {
Error, ErrorKind, ResultExt, Result;
}

// 定义额外的 `ErrorKind` 变体。使用`description` 和 `display` 调用定义自定义响应。
errors{
example1ErrorKind(t:String){
description("example error 1")
display("this is example error 1 {}",t)
}
example2ErrorKind(t:String){
description("example error 2")
display("this is example error 2{}",t)
}
}

// 把其他crate定义的error_chain中错误进行转换
// 在这种情况下,它将例如生成一个名为 `example3ErrorKind` 的 `ErrorKind` 变体,它又包含`other_crate::ErrorKind`,以及来自`other_crate::Error` 的转换。可选地,可以将一些属性添加到变体中。此部分可以为空。
links{
example3ErrorKind(other_crate::Error,other_crate::ErrorKind);
}

// 转换标准库中的错误
// 这些将被包裹在一个新的错误中,`ErrorKind::Fmt` 变体。
foreign_links{
Fmt(::std::fmt::Error);
Io(::std::io::Error);
}
}
}

fn foo() -> Result<()> {
// Err(ErrorKind::example1ErrorKind(String::from("foo error")).into())
// bail!(ErrorKind::example1ErrorKind(String::from("foo error")))
Err(ErrorKind::example1ErrorKind(String::from("foo error")))?
}



fn main() {
match foo() {
Ok(_) => {
println!("ok");
}
Err(e) => {
println!("result is: {}",e);
}
}
}

避免在错误转变过程中遗漏错误

error-chain crate 使得匹配函数返回的不同错误类型成为可能,并且相对简洁。ErrorKind 是枚举类型,可以确定错误类型。

下文实例使用 reqwest::blocking 来查询一个随机整数生成器的 web 服务,并将服务器响应的字符串转换为整数。Rust 标准库 reqwest 和 web 服务都可能会产生错误,所以使用 foreign_links 定义易于辨认理解的 Rust 错误。另外,用于 web 服务错误信息的 ErrorKind 变量,使用 error_chain! 宏的 errors 代码块定义。

use error_chain::error_chain;

error_chain! {
foreign_links {
Io(std::io::Error);
Reqwest(reqwest::Error);
ParseIntError(std::num::ParseIntError);
}
errors { RandomResponseError(t: String) }
}

fn parse_response(response: reqwest::blocking::Response) -> Result<u32> {
let mut body = response.text()?;
body.pop();
body
.parse::<u32>()
.chain_err(|| ErrorKind::RandomResponseError(body))
}

fn run() -> Result<()> {
let url =
format!("https://www.random.org/integers/?num=1&min=0&max=10&col=1&base=10&format=plain");
let response = reqwest::blocking::get(&url)?;
let random_value: u32 = parse_response(response)?;
println!("a random number between 0 and 10: {}", random_value);
Ok(())
}

fn main() {
if let Err(error) = run() {
match *error.kind() {
ErrorKind::Io(_) => println!("Standard IO error: {:?}", error),
ErrorKind::Reqwest(_) => println!("Reqwest error: {:?}", error),
ErrorKind::ParseIntError(_) => println!("Standard parse int error: {:?}", error),
ErrorKind::RandomResponseError(_) => println!("User defined error: {:?}", error),
_ => println!("Other error: {:?}", error),
}
}
}

获取复杂错误场景的回溯

本实例展示了如何处理一个复杂的错误场景,并且打印出错误回溯。依赖于 chain_err,通过附加新的错误来扩展错误信息。从而可以展开错误堆栈,这样提供了更好的上下文来理解错误的产生原因。

下述代码尝试将值 256 反序列化为 u8。首先 Serde 产生错误,然后是 csv,最后是用户代码。

use error_chain::error_chain;
use serde::Deserialize;

use std::fmt;

error_chain! {
foreign_links {
Reader(csv::Error);
}
}

#[derive(Debug, Deserialize)]
struct Rgb {
red: u8,
blue: u8,
green: u8,
}

impl Rgb {
fn from_reader(csv_data: &[u8]) -> Result<Rgb> {
let color: Rgb = csv::Reader::from_reader(csv_data)
.deserialize()
.nth(0)
.ok_or("Cannot deserialize the first CSV record")?
.chain_err(|| "Cannot deserialize RGB color")?;

Ok(color)
}
}

impl fmt::UpperHex for Rgb {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let hexa = u32::from(self.red) << 16 | u32::from(self.blue) << 8 | u32::from(self.green);
write!(f, "{:X}", hexa)
}
}

fn run() -> Result<()> {
let csv = "red,blue,green
102,256,204";

let rgb = Rgb::from_reader(csv.as_bytes()).chain_err(|| "Cannot read CSV data")?;
println!("{:?} to hexadecimal #{:X}", rgb, rgb);

Ok(())
}

fn main() {
if let Err(ref errors) = run() {
eprintln!("Error level - description");
errors
.iter()
.enumerate()
.for_each(|(index, error)| eprintln!("└> {} - {}", index, error));

if let Some(backtrace) = errors.backtrace() {
eprintln!("{:?}", backtrace);
}

// In a real use case, errors should handled. For example:
// ::std::process::exit(1);
}
}

错误回溯信息如下:
Error level - description
└> 0 - Cannot read CSV data
└> 1 - Cannot deserialize RGB color
└> 2 - CSV deserialize error: record 1 (line: 2, byte: 15): field 1: number too large to fit in target type
└> 3 - field 1: number too large to fit in target type

具体内容可以展开宏

cargo ristc -- -Z unstable-options --pretty=expanded