dsntk_common/
errors.rs

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