Skip to main content

mln_plugin/
error.rs

1//! Status codes and diagnostic errors returned by plugin host calls.
2
3use core::fmt;
4
5/// Status code returned by host calls.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Status {
8    InvalidArgument,
9    InvalidState,
10    WrongThread,
11    Unsupported,
12    NativeError,
13    Cancelled,
14    Busy,
15    TargetLost,
16    NotFound,
17    AlreadyExists,
18    Other(i32),
19}
20
21/// Error returned by plugin host calls, with an optional diagnostic message.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Error {
24    pub status: Status,
25    pub message: String,
26}
27
28impl Error {
29    #[must_use]
30    pub fn new(status: Status, message: impl Into<String>) -> Self {
31        Self { status, message: message.into() }
32    }
33
34    #[must_use]
35    pub fn invalid_argument(message: impl Into<String>) -> Self {
36        Self::new(Status::InvalidArgument, message)
37    }
38
39    #[must_use]
40    pub fn invalid_state(message: impl Into<String>) -> Self {
41        Self::new(Status::InvalidState, message)
42    }
43
44    #[must_use]
45    pub fn not_found(message: impl Into<String>) -> Self {
46        Self::new(Status::NotFound, message)
47    }
48
49    #[must_use]
50    pub fn already_exists(message: impl Into<String>) -> Self {
51        Self::new(Status::AlreadyExists, message)
52    }
53
54    #[must_use]
55    pub fn native(message: impl Into<String>) -> Self {
56        Self::new(Status::NativeError, message)
57    }
58}
59
60impl fmt::Display for Error {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        if self.message.is_empty() {
63            write!(f, "{:?}", self.status)
64        } else {
65            write!(f, "{:?}: {}", self.status, self.message)
66        }
67    }
68}
69
70impl std::error::Error for Error {}
71
72/// Result alias using [`Error`].
73pub type Result<T> = std::result::Result<T, Error>;