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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! An error handling library for portable unrecoverable errors.
//!
//! This crate provides,
//!
//! - [`Failure`] struct that represents an unrecoverable error with an error code, message and user-level backtrace
//!   - Error code and message are optional
//!   - Constituted with simple types ([`u32`], [`String`], and [`Vec`] of those)
//!     - Portable across process and language boundaries
//!     - Optional [`serde`] support ("serde" feature)
//!   - Doesn't implement [`std::error::Error`] trait
//! - [`OrFail`] trait
//!   - Backtrace location is appended to [`Failure`] each time when calling [`OrFail::or_fail()`]
//!   - [`bool`], [`Option<_>`] and [`Result<_, _>`](std::result::Result) implement [`OrFail`]
//!
//! # Examples
//!
//! ```
//! use orfail::{OrFail, Result};
//!
//! fn check_non_zero(n: isize) -> Result<()> {
//!     (n != 0).or_fail()?;
//!     Ok(())
//! }
//!
//! fn safe_div(x: isize, y: isize) -> Result<isize> {
//!     check_non_zero(y).or_fail()?;
//!     Ok(x / y)
//! }
//!
//! // OK
//! assert_eq!(safe_div(4, 2), Ok(2));
//!
//! // NG
//! assert_eq!(safe_div(4, 0).err().map(|e| e.to_string()),
//!            Some(
//! r#"failed due to "expected `true` but got `false`"
//!   at src/lib.rs:7
//!   at src/lib.rs:12
//! "#.to_owned()));
//! ```
#![warn(missing_docs)]

/// This crate specific [`Result`](std::result::Result) type.
pub type Result<T> = std::result::Result<T, Failure>;

/// [`Failure`] typically represents an unrecoverable error with an error code, message, and backtrace.
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Failure {
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// Error code.
    pub code: Option<u32>,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    /// Error message.
    pub message: Option<String>,

    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    /// Backtrace.
    pub backtrace: Vec<Location>,
}

impl Failure {
    /// Makes a new [`Failure`] instance whose backtrace contains the current caller location.
    #[track_caller]
    pub fn new() -> Self {
        Self::default()
    }

    /// Updates the error code of this [`Failure`] instance.
    pub fn code(mut self, code: u32) -> Self {
        self.code = Some(code);
        self
    }

    /// Updates the error message of this [`Failure`] instance.
    pub fn message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl Default for Failure {
    #[track_caller]
    fn default() -> Self {
        Self {
            code: None,
            message: None,
            backtrace: vec![Location::new()],
        }
    }
}

impl std::fmt::Debug for Failure {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl std::fmt::Display for Failure {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "failed")?;
        if let Some(code) = self.code {
            write!(f, " with error code '{code}'")?;
        }
        if let Some(message) = &self.message {
            write!(f, " due to {message:?}")?;
        }
        writeln!(f)?;
        for location in &self.backtrace {
            writeln!(f, "  at {}:{}", location.file, location.line)?;
        }
        Ok(())
    }
}

/// A location in the backtrace of a [`Failure`] instance.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Location {
    /// File name.
    pub file: String,

    /// Line number.
    pub line: u32,
}

impl Location {
    /// Makes a new [`Location`] instance containing the caller's file name and line number.
    #[track_caller]
    pub fn new() -> Self {
        let location = std::panic::Location::caller();
        Self {
            file: location.file().to_owned(),
            line: location.line(),
        }
    }
}

impl Default for Location {
    #[track_caller]
    fn default() -> Self {
        Self::new()
    }
}

/// This trait allows for converting a value into `Result<_, Failure>`.
pub trait OrFail: Sized {
    /// Success value type (used for the `Ok(_)` variant).
    type Value;

    /// Returns `Err(Failure<C>)` if `self` is a failure value.
    ///
    /// If `Err(_)` is returned, this method should add the current caller location to the backtrace of the resulting `Failure<C>`.
    fn or_fail(self) -> Result<Self::Value>;
}

impl OrFail for bool {
    type Value = ();

    #[track_caller]
    fn or_fail(self) -> Result<Self::Value> {
        if self {
            Ok(())
        } else {
            Err(Failure::new().message("expected `true` but got `false`"))
        }
    }
}

impl<T> OrFail for Option<T> {
    type Value = T;

    #[track_caller]
    fn or_fail(self) -> Result<Self::Value> {
        if let Some(value) = self {
            Ok(value)
        } else {
            Err(Failure::new().message("expected `Some(_)` but got `None`"))
        }
    }
}

impl<T, E: std::error::Error> OrFail for std::result::Result<T, E> {
    type Value = T;

    #[track_caller]
    fn or_fail(self) -> Result<Self::Value> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => Err(Failure::new().message(e.to_string())),
        }
    }
}

impl<T> OrFail for Result<T> {
    type Value = T;

    #[track_caller]
    fn or_fail(self) -> Result<Self::Value> {
        match self {
            Ok(value) => Ok(value),
            Err(mut failure) => {
                failure.backtrace.push(Location::new());
                Err(Failure {
                    code: failure.code,
                    message: failure.message,
                    backtrace: failure.backtrace,
                })
            }
        }
    }
}

/// Similar to [`std::todo!()`] but returning an `Err(Failure)` instead of panicking.
#[macro_export]
macro_rules! todo {
    () => {
        return Err($crate::Failure::new().message("not yet implemented"));
    };
}

/// Similar to [`std::unreachable!()`] but returning an `Err(Failure)` instead of panicking.
#[macro_export]
macro_rules! unreachable {
    () => {
        return Err($crate::Failure::new().message("internal error: entered unreachable code"));
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert!((true.or_fail() as Result<_>).is_ok());
        assert!((false.or_fail() as Result<_>).is_err());

        let failure: Failure = false.or_fail().err().unwrap();
        assert!(failure.code.is_none());
        assert!(failure.message.is_some());
        assert_eq!(failure.backtrace.len(), 1);

        let failure: Failure = false
            .or_fail()
            .map_err(|f| f.code(10))
            .or_fail()
            .err()
            .unwrap();
        assert_eq!(failure.code, Some(10));
        assert!(failure.message.is_some());
        assert_eq!(failure.backtrace.len(), 2);
    }
}