Skip to main content

dsntk_common/
errors.rs

1//! # Definition of the common result and error types
2
3/// Common result type.
4pub type Result<T, E = DsntkError> = std::result::Result<T, E>;
5
6/// Common trait to be implemented by structs defining a specific error.
7pub trait ToErrorMessage {
8  /// Convert error definition to a message string.
9  fn message(self) -> String;
10}
11
12/// Common error definition.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct DsntkError(String);
15
16impl std::fmt::Display for DsntkError {
17  /// Implementation of [Display](std::fmt::Display) trait for [DsntkError].
18  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19    write!(f, "{}", self.0)
20  }
21}
22
23impl DsntkError {
24  /// Creates a new [DsntkError] with specified source name and error message.
25  pub fn new(source: &str, message: &str) -> Self {
26    Self(format!("<{source}> {message}"))
27  }
28}
29
30impl<T> From<T> for DsntkError
31where
32  T: ToErrorMessage,
33{
34  /// Converts any type that implements [ToErrorMessage] trait to [DsntkError].
35  fn from(value: T) -> Self {
36    let error_type_name = std::any::type_name::<T>().split("::").last().unwrap_or("UnknownError");
37    DsntkError::new(error_type_name, &value.message())
38  }
39}