File: string_custom_error_pattern.rs

package info (click to toggle)
rust-failure 0.1.7-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 364 kB
  • sloc: sh: 37; makefile: 17
file content (76 lines) | stat: -rw-r--r-- 1,757 bytes parent folder | download | duplicates (23)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//! This example show the pattern "Strings and custom fail type" described in the book
extern crate core;
extern crate failure;

use core::fmt::{self, Display};
use failure::{Backtrace, Context, Fail, ResultExt};

fn main() {
    let err = err1().unwrap_err();
    // Print the error itself
    println!("error: {}", err);
    // Print the chain of errors that caused it
    for cause in Fail::iter_causes(&err) {
        println!("caused by: {}", cause);
    }
}

fn err1() -> Result<(), MyError> {
    // The context can be a String
    Ok(err2().context("err1".to_string())?)
}

fn err2() -> Result<(), MyError> {
    // The context can be a &'static str
    Ok(err3().context("err2")?)
}

fn err3() -> Result<(), MyError> {
    Ok(Err(MyError::from("err3"))?)
}

#[derive(Debug)]
pub struct MyError {
    inner: Context<String>,
}

impl Fail for MyError {
    fn cause(&self) -> Option<&Fail> {
        self.inner.cause()
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}

impl Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        Display::fmt(&self.inner, f)
    }
}

// Allows writing `MyError::from("oops"))?`
impl From<&'static str> for MyError {
    fn from(msg: &'static str) -> MyError {
        MyError {
            inner: Context::new(msg.into()),
        }
    }
}

// Allows adding more context via a String
impl From<Context<String>> for MyError {
    fn from(inner: Context<String>) -> MyError {
        MyError { inner }
    }
}

// Allows adding more context via a &str
impl From<Context<&'static str>> for MyError {
    fn from(inner: Context<&'static str>) -> MyError {
        MyError {
            inner: inner.map(|s| s.to_string()),
        }
    }
}