Skip to main content

ohlcv_ctl/
error.rs

1use std::{error::Error as StdError, fmt};
2
3/// Error type for the CLI.
4#[derive(Debug)]
5#[allow(clippy::module_name_repetitions)]
6pub enum Error {
7    /// Failed to ask password.
8    AskPassword(String, Box<inquire::error::InquireError>),
9    /// Unknown command name.
10    CommandName(String),
11    /// Configuration file is missing.
12    ConfigFile,
13    /// Failed to parse configuration file.
14    ConfigFormat(toml::de::Error),
15    /// Failed to read or write to a file.
16    Io(std::io::Error),
17    /// Error returned by the OHLCV crate.
18    Ohlcv(ohlcv::Error),
19}
20
21impl StdError for Error {
22    #[inline]
23    fn source(&self) -> Option<&(dyn StdError + 'static)> {
24        match self {
25            Self::AskPassword(_, err) => Some(err.as_ref()),
26            Self::CommandName(_) | Self::ConfigFile => None,
27            Self::ConfigFormat(err) => Some(err),
28            Self::Io(err) => Some(err),
29            Self::Ohlcv(err) => Some(err),
30        }
31    }
32}
33
34impl fmt::Display for Error {
35    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36        match self {
37            Self::AskPassword(name, err) => {
38                write!(f, "Failed to ask password for '{name}': {err}")
39            }
40            Self::CommandName(name) => write!(f, "Unknown command name: '{name}'"),
41            Self::ConfigFile => write!(f, "Configuration file is missing"),
42            Self::ConfigFormat(err) => err.fmt(f),
43            Self::Io(err) => err.fmt(f),
44            Self::Ohlcv(err) => err.fmt(f),
45        }
46    }
47}
48
49impl From<std::io::Error> for Error {
50    #[inline]
51    fn from(err: std::io::Error) -> Self {
52        Self::Io(err)
53    }
54}
55
56impl From<ohlcv::Error> for Error {
57    #[inline]
58    fn from(err: ohlcv::Error) -> Self {
59        Self::Ohlcv(err)
60    }
61}
62
63impl From<toml::de::Error> for Error {
64    #[inline]
65    fn from(err: toml::de::Error) -> Self {
66        Self::ConfigFormat(err)
67    }
68}