File: backtrace.rs

package info (click to toggle)
rust-snafu 0.7.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 724 kB
  • sloc: sh: 15; makefile: 4
file content (57 lines) | stat: -rw-r--r-- 1,509 bytes parent folder | download | duplicates (3)
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
#![cfg(feature="std")]
use snafu::{prelude::*, Backtrace, ErrorCompat};

type AnotherError = Box<dyn std::error::Error>;

#[derive(Debug, Snafu)]
enum Error {
    #[snafu(display("Invalid user {}:\n{}", user_id, backtrace))]
    InvalidUser { user_id: i32, backtrace: Backtrace },
    WithSource {
        source: AnotherError,
        backtrace: Backtrace,
    },
    WithSourceAndOtherInfo {
        user_id: i32,
        source: AnotherError,
        backtrace: Backtrace,
    },
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn example(user_id: i32) -> Result<()> {
    ensure!(user_id >= 42, InvalidUserSnafu { user_id });
    Ok(())
}

#[test]
fn display_can_access_backtrace() {
    let e = example(0).unwrap_err();
    let text = e.to_string();
    assert!(
        text.contains("disabled backtrace"),
        "{:?} does not contain expected text",
        text
    );
}

fn trigger() -> Result<(), AnotherError> {
    Err("boom".into())
}

#[test]
fn errors_with_sources_can_have_backtraces() {
    let e = trigger().context(WithSourceSnafu).unwrap_err();
    let backtrace = ErrorCompat::backtrace(&e).unwrap();
    assert!(backtrace.to_string().contains("disabled backtrace"));
}

#[test]
fn errors_with_sources_and_other_info_can_have_backtraces() {
    let e = trigger()
        .context(WithSourceAndOtherInfoSnafu { user_id: 42 })
        .unwrap_err();
    let backtrace = ErrorCompat::backtrace(&e).unwrap();
    assert!(backtrace.to_string().contains("disabled backtrace"));
}