Skip to main content

tauri_plugin_moonbase/
error.rs

1use serde::ser::SerializeStruct as _;
2use serde::{Serialize, Serializer};
3
4/// What a plugin command can fail with. Serialized for the frontend as
5/// `{ kind, message }`, where `kind` is the SDK's error type (`"apiError"`,
6/// `"licenseInvalid"`, ...) or one of the plugin's own (`"notLicensed"`,
7/// `"busy"`, `"internal"`).
8#[derive(Debug, thiserror::Error)]
9#[non_exhaustive]
10pub enum Error {
11    #[error(transparent)]
12    Moonbase(#[from] moonbase::Error),
13
14    /// The operation needs a license and none is loaded.
15    #[error("No license is loaded")]
16    NotLicensed,
17
18    /// Another operation that changes the license is still running.
19    #[error("{0}")]
20    Busy(String),
21
22    #[error(transparent)]
23    Tauri(#[from] tauri::Error),
24
25    #[error("{0}")]
26    Internal(String),
27}
28
29impl Error {
30    fn kind(&self) -> String {
31        match self {
32            Self::Moonbase(error) => serde_json::to_value(error.error_type())
33                .ok()
34                .and_then(|value| value.as_str().map(str::to_owned))
35                .unwrap_or_else(|| "unknown".into()),
36            Self::NotLicensed => "notLicensed".into(),
37            Self::Busy(_) => "busy".into(),
38            Self::Tauri(_) | Self::Internal(_) => "internal".into(),
39        }
40    }
41}
42
43impl Serialize for Error {
44    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
45        let mut out = serializer.serialize_struct("Error", 2)?;
46        out.serialize_field("kind", &self.kind())?;
47        out.serialize_field("message", &self.to_string())?;
48        out.end()
49    }
50}
51
52pub type Result<T, E = Error> = std::result::Result<T, E>;