ssbbot/src/error.rs

68 lines
1.9 KiB
Rust

//! Custom error type.
use std::io::Error as IoError;
use golgi::error::GolgiError;
use std::str::Utf8Error;
/// A custom error type encapsulating all possible errors for this library.
/// `From` implementations are provided for external error types, allowing
/// the `?` operator to be used on functions which return `Result<_, GolgiError>`.
#[derive(Debug)]
pub enum SsbBotError {
/// IO error with context.
Io {
/// The underlying IO error.
source: IoError,
/// Description of the error context.
context: String,
},
/// Error within golgi library
Golgi {
/// The underlying error
source: GolgiError,
},
/// Error decoding UTF8 string from bytes
Utf8Parse {
/// The underlying parse error.
source: Utf8Error,
},
}
impl std::error::Error for SsbBotError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
SsbBotError::Io { ref source, .. } => Some(source),
SsbBotError::Golgi { ref source } => Some(source),
SsbBotError::Utf8Parse { ref source } => Some(source),
}
}
}
impl std::fmt::Display for SsbBotError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &*self {
SsbBotError::Io { ref context, .. } => write!(f, "IO error: {}", context),
SsbBotError::Golgi { source } => write!(
f,
"Golgi encountered an error: {}",
source
),
SsbBotError::Utf8Parse { source } => {
write!(f, "Failed to deserialize UTF8 from bytes: {}", source)
}
}
}
}
impl From<Utf8Error> for SsbBotError {
fn from(err: Utf8Error) -> Self {
SsbBotError::Utf8Parse { source: err }
}
}
impl From<GolgiError> for SsbBotError {
fn from(err: GolgiError) -> Self {
SsbBotError::Golgi { source: err }
}
}