dynamo_runtime/protocols/
maybe_error.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::error::Error;
5
6pub trait MaybeError {
7    /// 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    /// Check if the current instance represents a success.
14    fn is_ok(&self) -> bool {
15        !self.is_err()
16    }
17
18    /// Check if the current instance represents an error.
19    fn is_err(&self) -> bool {
20        self.err().is_some()
21    }
22}
23
24#[cfg(test)]
25mod tests {
26    use super::*;
27
28    struct TestError {
29        message: String,
30    }
31    impl MaybeError for TestError {
32        fn from_err(err: Box<dyn Error + Send + Sync>) -> Self {
33            TestError {
34                message: err.to_string(),
35            }
36        }
37        fn err(&self) -> Option<anyhow::Error> {
38            Some(anyhow::Error::msg(self.message.clone()))
39        }
40    }
41
42    #[test]
43    fn test_maybe_error_default_implementations() {
44        let err = TestError::from_err(anyhow::Error::msg("Test error".to_string()).into());
45        assert_eq!(format!("{}", err.err().unwrap()), "Test error");
46        assert!(!err.is_ok());
47        assert!(err.is_err());
48    }
49}