bash_builtins/
errors.rs

1//! Types to handle errors.
2
3use crate::ffi;
4use std::fmt;
5use std::os::raw::c_int;
6
7/// The error type for [`Builtin::call`].
8///
9/// Usually, you don't need to construct this type manually. Instead, use the
10/// [`?` operator] for any [`Result`] in the body of the [`Builtin::call`]
11/// method, and errors will be converted to this type.
12///
13/// However, if you want to return a specific exit code, use the
14/// [`ExitCode`] variant.
15///
16/// [`?` operator]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
17/// [`Builtin::call`]: crate::Builtin::call
18/// [`ExitCode`]: Error::ExitCode
19/// [`Result`]: std::result::Result
20#[derive(Debug)]
21pub enum Error {
22    /// Syntax error in usage.
23    Usage,
24
25    /// Exit with a specific code.
26    ///
27    /// # Example
28    ///
29    /// ```
30    /// use bash_builtins::{Args, Builtin, Error::ExitCode, Result};
31    ///
32    /// # struct SomeName;
33    /// impl Builtin for SomeName {
34    ///     fn call(&mut self, args: &mut Args) -> Result<()> {
35    ///         // In this builtin, we return `127` if there are
36    ///         // no arguments.
37    ///         if args.is_empty() {
38    ///             return Err(ExitCode(127));
39    ///         }
40    ///
41    ///         // …
42    ///
43    ///         Ok(())
44    ///     }
45    /// }
46    /// ```
47    ExitCode(c_int),
48
49    /// Wrapper for any error.
50    ///
51    /// This variant is used when the builtin propagates any error inside
52    /// [`Builtin::call`].
53    ///
54    /// # Example
55    ///
56    /// ```
57    /// use std::fs;
58    /// use bash_builtins::{Args, Builtin, Error::ExitCode, Result};
59    ///
60    /// # struct SomeName;
61    /// impl Builtin for SomeName {
62    ///     fn call(&mut self, args: &mut Args) -> Result<()> {
63    /// #       let _ = args;
64    ///
65    ///         // fs::read can return an `io::Error`, which is wrapped
66    ///         // by `GenericError` and then used as the return value.
67    ///         let _ = fs::read("/some/config/file")?;
68    ///
69    ///         // …
70    ///
71    ///         Ok(())
72    ///     }
73    /// }
74    /// ```
75    ///
76    /// [`Builtin::call`]: crate::Builtin::call
77    GenericError(Box<dyn std::error::Error>),
78}
79
80impl Error {
81    /// Returns `true` if this error should be printed to [`stderr`] when
82    /// it is the result of [`Builtin::call`].
83    ///
84    /// [`Builtin::call`]: crate::Builtin::call
85    /// [`stderr`]: std::io::stderr
86    #[doc(hidden)]
87    pub fn print_on_return(&self) -> bool {
88        let ignore = matches!(self, Error::Usage | Error::ExitCode(_));
89        !ignore
90    }
91
92    /// Numeric exit code for the builtin invocation.
93    #[doc(hidden)]
94    pub fn exit_code(&self) -> c_int {
95        match self {
96            Error::Usage => ffi::exit::EX_USAGE,
97            Error::ExitCode(s) => *s,
98            _ => ffi::exit::EXECUTION_FAILURE,
99        }
100    }
101}
102
103impl fmt::Display for Error {
104    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
105        match self {
106            Error::Usage => fmt.write_str("usage error"),
107            Error::ExitCode(s) => write!(fmt, "exit code {}", s),
108            Error::GenericError(e) => e.fmt(fmt),
109        }
110    }
111}
112
113impl<E> From<E> for Error
114where
115    E: std::error::Error + 'static,
116{
117    fn from(error: E) -> Self {
118        Error::GenericError(Box::new(error))
119    }
120}
121
122/// A specialized [`Result`] type for this crate.
123///
124/// [`Result`]: std::result::Result
125pub type Result<T> = std::result::Result<T, Error>;