1use std::{fmt::Display, path::PathBuf};
6
7#[derive(Debug, thiserror::Error)]
8pub enum Error {
9 #[error("{0}: {1}")]
10 Context(String, Box<dyn std::error::Error + Send + Sync + 'static>),
11 #[error("{0}")]
12 GenericError(String),
13 #[error("failed to bundle project {0}")]
14 Bundler(#[from] Box<tauri_bundler::Error>),
15 #[error("{context} {path}: {error}")]
16 Fs {
17 context: &'static str,
18 path: PathBuf,
19 error: std::io::Error,
20 },
21 #[error("failed to run command {command}: {error}")]
22 CommandFailed {
23 command: String,
24 error: std::io::Error,
25 },
26 #[cfg(target_os = "macos")]
27 #[error(transparent)]
28 MacosSign(#[from] Box<tauri_macos_sign::Error>),
29}
30
31pub type Result<T> = std::result::Result<T, Error>;
33
34pub trait Context<T> {
35 fn context<C>(self, context: C) -> Result<T>
37 where
38 C: Display + Send + Sync + 'static;
39 fn with_context<C, F>(self, f: F) -> Result<T>
40 where
41 C: Display + Send + Sync + 'static,
42 F: FnOnce() -> C;
43}
44
45impl<T, E: std::error::Error + Send + Sync + 'static> Context<T> for std::result::Result<T, E> {
46 fn context<C>(self, context: C) -> Result<T>
47 where
48 C: Display + Send + Sync + 'static,
49 {
50 self.map_err(|e| Error::Context(context.to_string(), Box::new(e)))
51 }
52
53 fn with_context<C, F>(self, f: F) -> Result<T>
54 where
55 C: Display + Send + Sync + 'static,
56 F: FnOnce() -> C,
57 {
58 self.map_err(|e| Error::Context(f().to_string(), Box::new(e)))
59 }
60}
61
62impl<T> Context<T> for Option<T> {
63 fn context<C>(self, context: C) -> Result<T>
64 where
65 C: Display + Send + Sync + 'static,
66 {
67 self.ok_or_else(|| Error::GenericError(context.to_string()))
68 }
69
70 fn with_context<C, F>(self, f: F) -> Result<T>
71 where
72 C: Display + Send + Sync + 'static,
73 F: FnOnce() -> C,
74 {
75 self.ok_or_else(|| Error::GenericError(f().to_string()))
76 }
77}
78
79pub trait ErrorExt<T> {
80 fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T>;
81}
82
83impl<T> ErrorExt<T> for std::result::Result<T, std::io::Error> {
84 fn fs_context(self, context: &'static str, path: impl Into<PathBuf>) -> Result<T> {
85 self.map_err(|error| Error::Fs {
86 context,
87 path: path.into(),
88 error,
89 })
90 }
91}
92
93macro_rules! bail {
94 ($msg:literal $(,)?) => {
95 return Err(crate::Error::GenericError($msg.into()))
96 };
97 ($err:expr $(,)?) => {
98 return Err(crate::Error::GenericError($err))
99 };
100 ($fmt:expr, $($arg:tt)*) => {
101 return Err(crate::Error::GenericError(format!($fmt, $($arg)*)))
102 };
103}
104
105pub(crate) use bail;