Rust Error-Chain

Error-Chain是rust常用的错误处理库,目的是方便程序员更好的进行程序的错误管理。这就要说到默认库实现有什么不足。

传统的错误实现方式

需要为统一一个Error结构体,并且每一个成员都要实现fmt,display,from
具体可以看这篇文章

使用Error-Chain的方式

use main_crate::*;

pub mod other_crate{
    use error_chain::*;
    error_chain! {
        errors{

        }
    }
}

pub mod main_crate{
    use error_chain::*;
    use crate::other_crate;
    error_chain!{
    //定义当前crate的错误
        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中错误进行转换
        links{
            example3ErrorKind(other_crate::Error,other_crate::ErrorKind);
        }

        //转换标准库中的错误
        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库会通过声明宏的方式自动转换为如下的程序,具体内容可以展开宏
cargo ristc -- -Z unstable-options --pretty=expanded

use std::error::Error as StdError;
use std::sync::Arc;

#[derive(Debug)]
pub struct Error(pub ErrorKind,
                 pub Option<Box<StdError + Send>>,
                 pub Arc<error_chain::Backtrace>);

impl Error {
    pub fn kind(&self) -> &ErrorKind { ... }
    pub fn into_kind(self) -> ErrorKind { ... }
    pub fn iter(&self) -> error_chain::ErrorChainIter { ... }
    pub fn backtrace(&self) -> &error_chain::Backtrace { ... }
}

impl StdError for Error { ... }
impl Display for Error { ... }

#[derive(Debug)]
pub enum ErrorKind {
    Msg(String),
    example1ErrorKind(String),
    example2ErrorKind(String),
    example3ErrorKind(other_crate::ErrorKind),
    Fmt(::std::fmt::Error),
    Io(::std::io::Error),
}

所以通过这样的方式,就省去了我们大量的时间
最终输出结果为
result is:this is example error 1 foo error

参考资料:
官方文档说明
其他人的例子
https://users.rust-lang.org/t/announcing-error-chain-a-library-for-consistent-and-reliable-rust-error-handling/6133
https://brson.github.io/2016/11/30/starting-with-error-chain

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Error-chain Github crates.io 前言 错误和异常傻傻分不清,这里统称为错误吧。Rust ...
    kayryu阅读 2,203评论 0 1
  • 原文地址:https://github.com/baoyachi/rust-error-handle 1. 前言 ...
    包牙齿阅读 5,003评论 0 2
  • 简介 Rust 是最近几年开始兴起的编程语言,虽然目前还没看到要像 Go 一样”大火“的趋势。但是,官网的一些 f...
    linjinhe阅读 6,506评论 1 15
  • 错误:1000 SQLSTATE: HY000 (ER_HASHCHK)消息:hashchk 错误:1001 SQ...
    灼灼2015阅读 23,713评论 0 6
  • 蒋其润,11月1日。 我是个勇敢自信,对住人善良勇怕困难刻苦坚持奉行积极的人。 今天的我们在语文课上协会了作业,我...
    其其_aa93阅读 171评论 0 1