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
//! noodles errors.
use std::fmt;
/// An error kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Kind {
/// An I/O error.
Io,
/// An error that does not fall into any other error kind.
Other,
/// A parse error.
Parse,
/// A conversion error.
TryFrom,
}
#[derive(Debug)]
enum Context {
Simple(Kind),
Custom(Kind, Box<dyn std::error::Error + Send + Sync>),
}
/// A noodles error.
#[derive(Debug)]
pub struct Error {
context: Context,
}
impl Error {
/// Creates an error.
///
/// # Examples
///
/// ```
/// use noodles_core as core;
/// let error = core::Error::new(core::error::Kind::Other, "errno 1");
/// assert_eq!(error.kind(), core::error::Kind::Other);
/// ```
pub fn new<E>(kind: Kind, error: E) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Self {
context: Context::Custom(kind, error.into()),
}
}
/// Returns the error kind.
///
/// # Examples
///
/// ```
/// use noodles_core as core;
/// let error = core::Error::new(core::error::Kind::Other, "errno 1");
/// assert_eq!(error.kind(), core::error::Kind::Other);
/// ```
pub fn kind(&self) -> Kind {
match &self.context {
Context::Simple(kind) | Context::Custom(kind, _) => *kind,
}
}
}
impl From<Kind> for Error {
fn from(kind: Kind) -> Self {
Self {
context: Context::Simple(kind),
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::new(Kind::Io, e)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.context {
Context::Simple(kind) => write!(f, "{kind:?}"),
Context::Custom(_, e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.context {
Context::Simple(_) => None,
Context::Custom(_, e) => e.source(),
}
}
}