Skip to main content

ferogram_fsm/
error.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2//
3// ferogram: async Telegram MTProto client in Rust
4// https://github.com/ankit-chaubey/ferogram
5//
6// Licensed under either the MIT License or the Apache License 2.0.
7// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
8// https://github.com/ankit-chaubey/ferogram
9//
10// Feel free to use, modify, and share this code.
11// Please keep this notice when redistributing.
12
13use std::fmt;
14
15/// An error from a [`StateStorage`](crate::StateStorage) backend.
16#[derive(Debug)]
17pub struct StorageError {
18    message: String,
19    source: Option<Box<dyn std::error::Error + Send + Sync>>,
20}
21
22impl StorageError {
23    /// Create a storage error with a plain message.
24    pub fn new(message: impl Into<String>) -> Self {
25        Self {
26            message: message.into(),
27            source: None,
28        }
29    }
30
31    /// Create a storage error wrapping an underlying cause.
32    pub fn with_source(
33        message: impl Into<String>,
34        source: impl std::error::Error + Send + Sync + 'static,
35    ) -> Self {
36        Self {
37            message: message.into(),
38            source: Some(Box::new(source)),
39        }
40    }
41}
42
43impl fmt::Display for StorageError {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        write!(f, "state storage error: {}", self.message)?;
46        if let Some(ref src) = self.source {
47            write!(f, ": {src}")?;
48        }
49        Ok(())
50    }
51}
52
53impl std::error::Error for StorageError {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        self.source.as_ref().map(|e| e.as_ref() as _)
56    }
57}