cryptouri/
error.rs

1//! Error types
2
3use anomaly::{BoxError, Context};
4use std::{
5    fmt::{self, Display},
6    ops::Deref,
7};
8use thiserror::Error;
9
10/// Kinds of errors
11#[derive(Copy, Clone, Debug, Error, Eq, PartialEq)]
12pub enum ErrorKind {
13    /// Unknown or unsupported algorithm
14    #[error("unknown or unsupported algorithm")]
15    AlgorithmInvalid,
16
17    /// Checksum error
18    #[error("checksum error")]
19    ChecksumInvalid,
20
21    /// Error parsing CryptoUri syntax
22    #[error("parse error")]
23    ParseError,
24
25    /// Unknown CryptoUri scheme
26    #[error("unknown URI scheme")]
27    SchemeInvalid,
28}
29
30impl ErrorKind {
31    /// Add context to an [`ErrorKind`]
32    pub fn context(self, source: impl Into<BoxError>) -> Context<ErrorKind> {
33        Context::new(self, Some(source.into()))
34    }
35}
36
37/// Error type
38#[derive(Debug)]
39pub struct Error(Box<Context<ErrorKind>>);
40
41impl Deref for Error {
42    type Target = Context<ErrorKind>;
43
44    fn deref(&self) -> &Context<ErrorKind> {
45        &self.0
46    }
47}
48
49impl Display for Error {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        write!(f, "{}", self.0)
52    }
53}
54
55impl std::error::Error for Error {
56    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57        self.0.source()
58    }
59}
60
61impl From<ErrorKind> for Error {
62    fn from(kind: ErrorKind) -> Self {
63        Context::new(kind, None).into()
64    }
65}
66
67impl From<Context<ErrorKind>> for Error {
68    fn from(context: Context<ErrorKind>) -> Self {
69        Error(Box::new(context))
70    }
71}
72
73impl From<subtle_encoding::Error> for Error {
74    fn from(err: subtle_encoding::Error) -> Error {
75        match err {
76            subtle_encoding::Error::ChecksumInvalid => ErrorKind::ChecksumInvalid,
77            _ => ErrorKind::ParseError,
78        }
79        .into()
80    }
81}