Skip to main content

clack_host/host/
error.rs

1use core::fmt;
2use core::fmt::{Debug, Display, Formatter};
3use std::error::Error;
4
5/// A generic, type-erased error type for host-originating errors.
6///
7/// Errors are type-erased because the CLAP API does not support extracting error information from
8/// a plugin or host, only that an error happened.
9///
10/// Errors originating from a user-provided host callback implementation are simply logged through
11/// the host's provided logging facilities if available, or the standard error output ([`stderr`])
12/// if not.
13///
14/// This error can be constructed either from any existing [`Error`] type, or from an arbitrary
15/// error message.
16///
17/// # Example
18///
19/// ```
20/// use std::io;
21/// use clack_host::prelude::HostError;
22///
23/// fn foo () -> io::Result<()> {
24///     /* ... */
25///     # Ok(())
26/// }
27///
28/// fn perform(valid: bool) -> Result<(), HostError> {
29///     if !valid {
30///         return Err(HostError::Message("Invalid value"))
31///     }
32///     /* ... */
33///     foo()?;
34///     /* ... */
35///     Ok(())
36/// }
37/// # perform(true).unwrap()
38/// ```
39///
40/// [`stderr`]: std::io::stderr
41#[derive(Debug)]
42pub enum HostError {
43    /// A generic, type-erased error.
44    Error(Box<dyn Error + 'static>),
45    /// A constant string message to be displayed.
46    Message(&'static str),
47}
48
49impl Display for HostError {
50    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
51        match self {
52            HostError::Error(e) => Display::fmt(&e, f),
53            HostError::Message(msg) => f.write_str(msg),
54        }
55    }
56}
57
58impl<E: Error + 'static> From<E> for HostError {
59    #[inline]
60    fn from(e: E) -> Self {
61        HostError::Error(Box::new(e))
62    }
63}