about summary refs log tree commit diff
path: root/src/error.rs
blob: a0aa68e6c495d561dd27157d9264a08460128308 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::fmt::{ self, Display };

#[derive(Debug)]
pub struct Error(String);
pub type Result<T> = std::result::Result<T, Error>;


impl Error {
  pub fn log(&self) {
    println!("{}", self);
  }

  pub fn custom(text: &str) -> Self {
    Error(text.to_string())
  }
}


impl Display for Error {
  fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(formatter, "Error: {}", self.0)
  }
}

impl From<std::env::VarError> for Error {
  fn from(error: std::env::VarError) -> Error {
    Error(format!("Environment variable: {}", error))
  }
}

impl From<std::io::Error> for Error {
  fn from(error: std::io::Error) -> Error {
    Error(format!("I/O: {}", error))
  }
}

impl From<std::num::ParseIntError> for Error {
  fn from(error: std::num::ParseIntError) -> Error {
    Error(format!("integer syntax: {}", error))
  }
}

impl<T> From<std::sync::PoisonError<T>> for Error {
  fn from(error: std::sync::PoisonError<T>) -> Error {
    Error(format!("Lock poisoned: {}", error))
  }
}

impl From<async_channel::RecvError> for Error {
  fn from(error: async_channel::RecvError) -> Error {
    Error(format!("Channel receive: {}", error))
  }
}

impl<T> From<async_channel::SendError<T>> for Error {
  fn from(error: async_channel::SendError<T>) -> Error {
    Error(format!("Channel send: {}", error))
  }
}

impl From<rustix::io::Errno> for Error {
  fn from(error: rustix::io::Errno) -> Error {
    Error(format!("Unix system-call: {}", error))
  }
}


impl From<xcb::Error> for Error {
  fn from(error: xcb::Error) -> Error {
    match error {
      xcb::Error::Connection(error) => error.into(),
      xcb::Error::Protocol(error) => error.into(),
    }
  }
}

impl From<xcb::ConnError> for Error {
  fn from(error: xcb::ConnError) -> Error {
    Error(format!("X connection: {}", error))
  }
}

impl From<xcb::ProtocolError> for Error {
  fn from(error: xcb::ProtocolError) -> Error {
    Error(format!("X protocol: {}", error))
  }
}

impl From<xml::reader::Error> for Error {
  fn from(error: xml::reader::Error) -> Error {
    Error(format!("XML parsing: {}", error))
  }
}


pub fn log_and_ignore_errors<T, E: Into<Error>>(
           result: std::result::Result<T, E>)
{
  match result {
    Ok(_) => (),
    Err(error) => Into::<Error>::into(error).log()
  }
}