1use std::path::PathBuf;
2
3use miette::Diagnostic;
4use thiserror::Error;
5
6#[derive(Error, Debug, Diagnostic)]
8pub enum Error {
9 #[error("Entry not found for key {1:?} in cache {0:?}")]
12 #[diagnostic(code(cacache::entry_not_found), url(docsrs))]
13 EntryNotFound(PathBuf, String),
14
15 #[error("Size check failed.\n\tWanted: {0}\n\tActual: {1}")]
17 #[diagnostic(code(cacache::size_mismatch), url(docsrs))]
18 SizeMismatch(usize, usize),
19
20 #[error("{1}")]
22 #[diagnostic(code(cacache::io_error), url(docsrs))]
23 IoError(#[source] std::io::Error, String),
24
25 #[error("{1}")]
27 #[diagnostic(code(cacache::serde_error), url(docsrs))]
28 SerdeError(#[source] serde_json::Error, String),
29
30 #[error(transparent)]
32 #[diagnostic(code(cacache::integrity_error), url(docsrs))]
33 IntegrityError(#[from] ssri::Error),
34}
35
36pub type Result<T> = std::result::Result<T, Error>;
38
39pub trait IoErrorExt<T> {
40 fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T>;
41}
42
43impl<T> IoErrorExt<T> for std::result::Result<T, std::io::Error> {
44 fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T> {
45 match self {
46 Ok(t) => Ok(t),
47 Err(e) => Err(Error::IoError(e, f())),
48 }
49 }
50}
51
52impl<T> IoErrorExt<T> for std::result::Result<T, serde_json::Error> {
53 fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T> {
54 match self {
55 Ok(t) => Ok(t),
56 Err(e) => Err(Error::SerdeError(e, f())),
57 }
58 }
59}
60
61pub fn io_error(err: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> std::io::Error {
62 std::io::Error::new(std::io::ErrorKind::Other, err)
63}