maybe_error.rs 1.31 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
// SPDX-License-Identifier: Apache-2.0

use std::error::Error;

pub trait MaybeError {
    /// Construct an instance from an error.
8
    fn from_err(err: Box<dyn Error + Send + Sync>) -> Self;
9
10

    /// Construct into an error instance.
11
    fn err(&self) -> Option<anyhow::Error>;
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

    /// Check if the current instance represents a success.
    fn is_ok(&self) -> bool {
        !self.is_err()
    }

    /// Check if the current instance represents an error.
    fn is_err(&self) -> bool {
        self.err().is_some()
    }
}

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

    struct TestError {
        message: String,
    }
    impl MaybeError for TestError {
32
        fn from_err(err: Box<dyn Error + Send + Sync>) -> Self {
33
34
35
36
            TestError {
                message: err.to_string(),
            }
        }
37
38
        fn err(&self) -> Option<anyhow::Error> {
            Some(anyhow::Error::msg(self.message.clone()))
39
40
41
42
43
44
45
46
47
48
49
        }
    }

    #[test]
    fn test_maybe_error_default_implementations() {
        let err = TestError::from_err(anyhow::Error::msg("Test error".to_string()).into());
        assert_eq!(format!("{}", err.err().unwrap()), "Test error");
        assert!(!err.is_ok());
        assert!(err.is_err());
    }
}