hapi_rs/
errors.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::session::Session;

pub use crate::ffi::raw::{HapiResult, StatusType, StatusVerbosity};
use std::borrow::Cow;

pub type Result<T> = std::result::Result<T, HapiError>;

/// Error type returned by all APIs
// TODO: This should really be an Enum.
pub struct HapiError {
    /// A specific error type.
    pub kind: Kind,
    /// Context error messages.
    pub contexts: Vec<Cow<'static, str>>,
    /// Error message from server or static if server couldn't respond.
    pub server_message: Option<Cow<'static, str>>,
}

// This special case for TryFrom<T, Error = HapiError> where conversion can't fail.
// for example when "impl TryInto<AttributeName>" receives AttributeName.
impl From<std::convert::Infallible> for HapiError {
    fn from(_: std::convert::Infallible) -> Self {
        unreachable!()
    }
}

pub(crate) trait ErrorContext<T> {
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Into<Cow<'static, str>>;

    #[allow(unused)]
    fn with_context<C, F>(self, func: F) -> Result<T>
    where
        C: Into<Cow<'static, str>>,
        F: FnOnce() -> C;
}

impl<T> ErrorContext<T> for Result<T> {
    fn context<C>(self, context: C) -> Result<T>
    where
        C: Into<Cow<'static, str>>,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(mut error) => {
                error.contexts.push(context.into());
                Err(error)
            }
        }
    }

    fn with_context<C, F>(self, func: F) -> Result<T>
    where
        C: Into<Cow<'static, str>>,
        F: FnOnce() -> C,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(mut error) => {
                error.contexts.push(func().into());
                Err(error)
            }
        }
    }
}

#[derive(Debug)]
#[non_exhaustive]
pub enum Kind {
    /// Error returned by ffi calls
    Hapi(HapiResult),
    /// CString contains null byte
    NullByte(std::ffi::NulError),
    /// String is not a valid utf-8
    Utf8Error(std::string::FromUtf8Error),
    /// IO Error
    Io(std::io::Error),
    /// Misc error message from this crate.
    Internal(Cow<'static, str>),
}

impl Kind {
    fn description(&self) -> &str {
        use HapiResult::*;

        match self {
            Kind::Hapi(Success) => "SUCCESS",
            Kind::Hapi(Failure) => "FAILURE",
            Kind::Hapi(AlreadyInitialized) => "ALREADY_INITIALIZED",
            Kind::Hapi(NotInitialized) => "NOT_INITIALIZED",
            Kind::Hapi(CantLoadfile) => "CANT_LOADFILE",
            Kind::Hapi(ParmSetFailed) => "PARM_SET_FAILED",
            Kind::Hapi(InvalidArgument) => "INVALID_ARGUMENT",
            Kind::Hapi(CantLoadGeo) => "CANT_LOAD_GEO",
            Kind::Hapi(CantGeneratePreset) => "CANT_GENERATE_PRESET",
            Kind::Hapi(CantLoadPreset) => "CANT_LOAD_PRESET",
            Kind::Hapi(AssetDefAlreadyLoaded) => "ASSET_DEF_ALREADY_LOADED",
            Kind::Hapi(NoLicenseFound) => "NO_LICENSE_FOUND",
            Kind::Hapi(DisallowedNcLicenseFound) => "DISALLOWED_NC_LICENSE_FOUND",
            Kind::Hapi(DisallowedNcAssetWithCLicense) => "DISALLOWED_NC_ASSET_WITH_C_LICENSE",
            Kind::Hapi(DisallowedNcAssetWithLcLicense) => "DISALLOWED_NC_ASSET_WITH_LC_LICENSE",
            Kind::Hapi(DisallowedLcAssetWithCLicense) => "DISALLOWED_LC_ASSET_WITH_C_LICENSE",
            Kind::Hapi(DisallowedHengineindieW3partyPlugin) => {
                "DISALLOWED_HENGINEINDIE_W_3PARTY_PLUGIN"
            }
            Kind::Hapi(AssetInvalid) => "ASSET_INVALID",
            Kind::Hapi(NodeInvalid) => "NODE_INVALID",
            Kind::Hapi(UserInterrupted) => "USER_INTERRUPTED",
            Kind::Hapi(InvalidSession) => "INVALID_SESSION",
            Kind::NullByte(_) => "String contains null byte!",
            Kind::Utf8Error(_) => "String is not UTF-8!",
            Kind::Internal(s) => s,
            Kind::Io(_) => "IO Error",
        }
    }
}

impl From<HapiResult> for HapiError {
    fn from(r: HapiResult) -> Self {
        HapiError {
            kind: Kind::Hapi(r),
            contexts: Vec::new(),
            server_message: None,
        }
    }
}

impl From<std::io::Error> for HapiError {
    fn from(value: std::io::Error) -> Self {
        HapiError {
            kind: Kind::Io(value),
            contexts: Vec::new(),
            server_message: None,
        }
    }
}

impl HapiError {
    pub(crate) fn new(
        kind: Kind,
        mut static_message: Option<Cow<'static, str>>,
        server_message: Option<Cow<'static, str>>,
    ) -> HapiError {
        let mut contexts = vec![];
        if let Some(m) = static_message.take() {
            contexts.push(m);
        }
        HapiError {
            kind,
            contexts,
            server_message,
        }
    }
    pub(crate) fn internal<M: Into<Cow<'static, str>>>(message: M) -> Self {
        HapiError {
            kind: Kind::Internal(message.into()),
            server_message: None,
            contexts: vec![],
        }
    }
}

impl std::fmt::Display for HapiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            Kind::Hapi(_) => {
                write!(f, "[{}]: ", self.kind.description())?;
                if let Some(ref msg) = self.server_message {
                    write!(f, "[Engine Message]: {}", msg)?;
                }
                if !self.contexts.is_empty() {
                    writeln!(f)?; // blank line
                }
                for (n, msg) in self.contexts.iter().enumerate() {
                    writeln!(f, "\t{}. {}", n, msg)?;
                }
                Ok(())
            }
            Kind::NullByte(e) => unsafe {
                let text = e.clone().into_vec();
                // SAFETY: We don't care about utf8 for error reporting I think
                let text = std::str::from_utf8_unchecked(&text);
                write!(f, "{e} in string \"{}\"", text)
            },
            Kind::Utf8Error(e) => unsafe {
                // SAFETY: We don't care about utf8 for error reporting I think
                let text = std::str::from_utf8_unchecked(e.as_bytes());
                write!(f, "{e} in string \"{}\"", text)
            },
            Kind::Io(e) => {
                write!(f, "{}", e)
            }
            Kind::Internal(e) => {
                write!(f, "[Internal Error]: {e}")
            }
        }
    }
}

impl std::fmt::Debug for HapiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl From<std::ffi::NulError> for HapiError {
    fn from(e: std::ffi::NulError) -> Self {
        HapiError::new(Kind::NullByte(e), None, None)
    }
}

impl From<std::string::FromUtf8Error> for HapiError {
    fn from(e: std::string::FromUtf8Error) -> Self {
        HapiError::new(Kind::Utf8Error(e), None, None)
    }
}

impl From<&str> for HapiError {
    fn from(value: &str) -> Self {
        HapiError::new(Kind::Internal(Cow::Owned(value.to_string())), None, None)
    }
}

impl std::error::Error for HapiError {}

impl HapiResult {
    pub(crate) fn check_err<F, M>(self, session: &Session, context: F) -> Result<()>
    where
        M: Into<Cow<'static, str>>,
        F: FnOnce() -> M,
    {
        match self {
            HapiResult::Success => Ok(()),
            _err => {
                let server_message = session
                    .get_status_string(StatusType::CallResult, StatusVerbosity::All)
                    .map(Cow::Owned)
                    .unwrap_or_else(|_| Cow::Borrowed("Could not retrieve error message"));
                let mut err = HapiError::new(Kind::Hapi(self), None, Some(server_message));
                err.contexts.push(context().into());
                Err(err)
            }
        }
    }

    pub(crate) fn error_message<I: Into<Cow<'static, str>>>(self, message: I) -> Result<()> {
        match self {
            HapiResult::Success => Ok(()),
            _err => {
                let mut err = HapiError::new(
                    Kind::Hapi(self),
                    None,
                    Some(Cow::Borrowed("Server error message unavailable")),
                );
                err.contexts.push(message.into());
                Err(err)
            }
        }
    }
}