Skip to main content

onionlink_core/
error.rs

1use std::fmt;
2
3pub type Result<T> = std::result::Result<T, Error>;
4
5#[derive(Debug, Clone)]
6pub struct Error {
7    message: String,
8}
9
10impl Error {
11    pub fn new(message: impl Into<String>) -> Self {
12        Self {
13            message: message.into(),
14        }
15    }
16}
17
18impl fmt::Display for Error {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        f.write_str(&self.message)
21    }
22}
23
24impl std::error::Error for Error {}
25
26impl From<std::io::Error> for Error {
27    fn from(value: std::io::Error) -> Self {
28        Self::new(value.to_string())
29    }
30}
31
32impl From<std::num::ParseIntError> for Error {
33    fn from(value: std::num::ParseIntError) -> Self {
34        Self::new(value.to_string())
35    }
36}
37
38impl From<std::str::Utf8Error> for Error {
39    fn from(value: std::str::Utf8Error) -> Self {
40        Self::new(value.to_string())
41    }
42}
43
44impl From<base64::DecodeError> for Error {
45    fn from(value: base64::DecodeError) -> Self {
46        Self::new(format!("base64 decode failed: {value}"))
47    }
48}
49
50impl From<rustls::Error> for Error {
51    fn from(value: rustls::Error) -> Self {
52        Self::new(value.to_string())
53    }
54}
55
56impl From<chrono::ParseError> for Error {
57    fn from(value: chrono::ParseError) -> Self {
58        Self::new(value.to_string())
59    }
60}
61
62pub fn err<T>(message: impl Into<String>) -> Result<T> {
63    Err(Error::new(message))
64}
65
66pub fn ensure(ok: bool, message: impl Into<String>) -> Result<()> {
67    if ok {
68        Ok(())
69    } else {
70        Err(Error::new(message))
71    }
72}