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