| 1 |
use std::fmt::Display; |
| 2 |
use std::panic::Location; |
| 3 |
|
| 4 |
use gio::glib; |
| 5 |
|
| 6 |
pub type Result<T> = std::result::Result<T, Error>; |
| 7 |
|
| 8 |
#[derive(Debug)] |
| 9 |
pub struct Error { |
| 10 |
kind: ErrorKind, |
| 11 |
location: String, |
| 12 |
} |
| 13 |
|
| 14 |
impl Error { |
| 15 |
#[track_caller] |
| 16 |
pub fn other(err: impl Display) -> Self { |
| 17 |
Self { |
| 18 |
kind: ErrorKind::Other(err.to_string()), |
| 19 |
location: location(), |
| 20 |
} |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
impl std::fmt::Display for Error { |
| 25 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 26 |
write!( |
| 27 |
f, |
| 28 |
"{}: {}: {}", |
| 29 |
env!("CARGO_PKG_NAME"), |
| 30 |
self.location, |
| 31 |
self.kind |
| 32 |
) |
| 33 |
} |
| 34 |
} |
| 35 |
impl std::error::Error for Error {} |
| 36 |
|
| 37 |
#[derive(Debug)] |
| 38 |
pub enum ErrorKind { |
| 39 |
GLibBool(glib::BoolError), |
| 40 |
Other(String), |
| 41 |
StdIo(std::io::Error), |
| 42 |
GLib(glib::Error), |
| 43 |
} |
| 44 |
|
| 45 |
impl std::fmt::Display for ErrorKind { |
| 46 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 47 |
match self { |
| 48 |
Self::GLibBool(err) => f.write_str(&err.to_string()), |
| 49 |
Self::Other(err) => f.write_str(err), |
| 50 |
Self::StdIo(err) => f.write_str(&err.to_string()), |
| 51 |
Self::GLib(err) => f.write_str(&err.to_string()), |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
impl From<glib::BoolError> for Error { |
| 57 |
#[track_caller] |
| 58 |
fn from(value: glib::BoolError) -> Self { |
| 59 |
Self { |
| 60 |
kind: ErrorKind::GLibBool(value), |
| 61 |
location: location(), |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
impl From<std::io::Error> for Error { |
| 67 |
#[track_caller] |
| 68 |
fn from(value: std::io::Error) -> Self { |
| 69 |
Self { |
| 70 |
kind: ErrorKind::StdIo(value), |
| 71 |
location: location(), |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
impl From<glib::Error> for Error { |
| 77 |
#[track_caller] |
| 78 |
fn from(value: glib::Error) -> Self { |
| 79 |
Self { |
| 80 |
kind: ErrorKind::GLib(value), |
| 81 |
location: location(), |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
#[track_caller] |
| 87 |
fn location() -> String { |
| 88 |
let location = Location::caller(); |
| 89 |
let path = location |
| 90 |
.file() |
| 91 |
.strip_prefix(env!("CARGO_MANIFEST_DIR")) |
| 92 |
.and_then(|x| x.strip_prefix("/")) |
| 93 |
.unwrap_or(location.file()); |
| 94 |
|
| 95 |
format!("{path}:{}:{}", location.line(), location.column()) |
| 96 |
} |