dynamo_runtime/protocols/maybe_error.rs
1// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::error::Error;
17
18pub trait MaybeError {
19 /// Construct an instance from an error.
20 fn from_err(err: Box<dyn Error + Send + Sync>) -> Self;
21
22 /// Construct into an error instance.
23 fn err(&self) -> Option<anyhow::Error>;
24
25 /// Check if the current instance represents a success.
26 fn is_ok(&self) -> bool {
27 !self.is_err()
28 }
29
30 /// Check if the current instance represents an error.
31 fn is_err(&self) -> bool {
32 self.err().is_some()
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 struct TestError {
41 message: String,
42 }
43 impl MaybeError for TestError {
44 fn from_err(err: Box<dyn Error + Send + Sync>) -> Self {
45 TestError {
46 message: err.to_string(),
47 }
48 }
49 fn err(&self) -> Option<anyhow::Error> {
50 Some(anyhow::Error::msg(self.message.clone()))
51 }
52 }
53
54 #[test]
55 fn test_maybe_error_default_implementations() {
56 let err = TestError::from_err(anyhow::Error::msg("Test error".to_string()).into());
57 assert_eq!(format!("{}", err.err().unwrap()), "Test error");
58 assert!(!err.is_ok());
59 assert!(err.is_err());
60 }
61}