Skip to main content

mlua_isle/
error.rs

1//! Error types for mlua-isle.
2//!
3//! One error type, [`IsleError`], is returned by every public function,
4//! on the actors and on the in-thread layer ([`runtime`](crate::runtime)).
5//! A Lua error crosses to Rust as a [`LuaFailure`]: its kind, the message
6//! as Lua prints it, the traceback, and (with the `serde` feature) the
7//! raised value.  It is built on the VM thread, so it is `Send`.
8//!
9//! Cancellation is a value, not a message: the cancel hook and
10//! [`cancellable`](crate::runtime::cancellable) raise
11//! `mlua::Error::external(Cancelled)`, and Rust recognises it by
12//! downcasting (see [`Cancelled`]).
13
14use std::fmt;
15
16/// Errors returned by Isle operations.
17///
18/// Match on the variant; the Lua error of a request or root is
19/// [`IsleError::Lua`]:
20///
21/// ```rust
22/// use mlua_isle::{Isle, IsleError, LuaErrorKind};
23///
24/// let isle = Isle::spawn(|_| Ok(())).unwrap();
25/// match isle.eval::<()>("error('boom')") {
26///     Err(IsleError::Lua(f)) => {
27///         assert_eq!(f.kind, LuaErrorKind::Runtime);
28///         assert!(f.message.ends_with("boom"));
29///     }
30///     other => panic!("unexpected: {other:?}"),
31/// }
32/// isle.shutdown().unwrap();
33/// ```
34#[derive(Debug, thiserror::Error)]
35#[non_exhaustive]
36pub enum IsleError {
37    /// The Lua VM thread has already shut down.
38    #[error("isle shut down")]
39    Shutdown,
40
41    /// The operation was cancelled via [`CancelToken`](crate::CancelToken).
42    #[error("cancelled")]
43    Cancelled,
44
45    /// A request or root raised a Lua error.
46    #[error("lua error: {0}")]
47    Lua(LuaFailure),
48
49    /// The init closure failed (or, for the kinds noted on
50    /// [`LuaErrorKind::External`], the VM thread could not be set up).
51    #[error("init error: {0}")]
52    Init(LuaFailure),
53
54    /// `call` / `coroutine_call` named a global that is not a function.
55    /// Carries the name.
56    #[error("function '{0}' not found")]
57    NotFound(String),
58
59    /// The Lua thread panicked.  Carries the panic message when the
60    /// payload is a `&str` or a `String`.
61    #[error("lua thread panicked{}", .0.as_deref().map(|m| format!(": {m}")).unwrap_or_default())]
62    ThreadPanic(Option<String>),
63
64    /// The request channel is full (backpressure).
65    ///
66    /// Only returned by [`AsyncIsle`](crate::AsyncIsle) `spawn_*` methods
67    /// when the bounded channel has no capacity.  Unlike [`Shutdown`](Self::Shutdown),
68    /// this is a transient condition — the Lua thread is still alive and
69    /// retrying may succeed.
70    #[cfg(feature = "tokio")]
71    #[error("channel full (backpressure)")]
72    ChannelFull,
73
74    /// Failed to receive response from the Lua thread.
75    ///
76    /// The response channel was dropped before a result was sent.  This
77    /// typically means the Lua thread panicked or was shut down while a
78    /// request was in flight.
79    #[error("recv failed")]
80    RecvFailed,
81
82    /// All pool slots are in use and no Isle is available.
83    #[cfg(feature = "pool")]
84    #[error("pool exhausted (max_size={0})")]
85    PoolExhausted(usize),
86
87    /// Pool internal lock poisoned (another thread panicked while holding the lock).
88    #[cfg(feature = "pool")]
89    #[error("pool lock poisoned: {0}")]
90    PoolPoisoned(String),
91}
92
93/// What kind of Lua error a [`LuaFailure`] is.
94///
95/// Taken from the [`mlua::Error`] variant when the error was raised by
96/// mlua or by Rust code; a value raised from Lua with `error(v)` is
97/// [`Runtime`](Self::Runtime).
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99#[non_exhaustive]
100pub enum LuaErrorKind {
101    /// A Lua runtime error: `error(v)` in Lua, or an operation on the
102    /// wrong type (`mlua::Error::RuntimeError`).
103    Runtime,
104    /// The chunk did not compile (`mlua::Error::SyntaxError`).
105    Syntax,
106    /// The allocator refused memory (`mlua::Error::MemoryError`).
107    Memory,
108    /// A Rust function called from Lua returned `Err`
109    /// (`mlua::Error::CallbackError`).  This is the kind of a host
110    /// function that returns `Err(mlua::Error::external(e))` and is
111    /// called from Lua: mlua wraps the error in a `CallbackError` on
112    /// the way through Lua.
113    Callback,
114    /// A Rust error that did not pass through a Lua call
115    /// (`mlua::Error::ExternalError`), for example one returned by an
116    /// `exec` closure.  Also the kind of an [`IsleError::Init`] that is
117    /// not a Lua error: the OS refused to start the VM thread, the
118    /// thread's tokio runtime could not be built, or a pool was
119    /// configured with `max_size == 0`.
120    External,
121    /// A value did not convert between Lua and Rust
122    /// (`FromLuaConversionError`, `BadArgument`, serde errors).
123    Conversion,
124    /// Any other `mlua::Error` variant.
125    Other,
126}
127
128/// A Lua error, as it crosses from the VM thread to Rust.
129///
130/// Built on the VM thread from the raised value (or from the
131/// [`mlua::Error`] when the error came from Rust or from mlua), so it is
132/// `Send + Sync`.  The raw value itself stays on the Lua side: a host
133/// that needs it (an error object with a metatable, say) catches it
134/// with `pcall` in Lua.
135///
136/// `Display` prints [`message`](Self::message).
137#[derive(Debug, Clone)]
138#[non_exhaustive]
139pub struct LuaFailure {
140    /// The kind of error.
141    pub kind: LuaErrorKind,
142    /// The error as Lua prints it: `tostring(err)` on the VM thread
143    /// (so a `__tostring` metamethod is honoured).  For an error that
144    /// came from Rust, its `Display` (for a `CallbackError`, the
145    /// innermost cause; for a `RuntimeError`, the message without the
146    /// traceback).
147    pub message: String,
148    /// The Lua stack traceback at the point of the error, when one was
149    /// taken (errors raised in Lua and errors from Rust functions called
150    /// from Lua have one; an error before any Lua ran, such as a syntax
151    /// error, does not).
152    pub traceback: Option<String>,
153    /// The raised value converted to JSON, when it converts (tables of
154    /// strings / numbers / booleans, and those values themselves).
155    /// `None` for values that do not (functions, userdata, cyclic
156    /// tables) and for errors that came from Rust.
157    #[cfg(feature = "serde")]
158    pub value: Option<serde_json::Value>,
159}
160
161impl LuaFailure {
162    /// A failure of `kind` with `message` and no traceback (or value).
163    ///
164    /// For an `exec` closure that reports its own error:
165    /// `Err(IsleError::Lua(LuaFailure::new(LuaErrorKind::Runtime, "bad input")))`.
166    pub fn new(kind: LuaErrorKind, message: impl Into<String>) -> Self {
167        Self {
168            kind,
169            message: message.into(),
170            traceback: None,
171            #[cfg(feature = "serde")]
172            value: None,
173        }
174    }
175
176    /// Build a failure from an [`mlua::Error`]: the kind from the
177    /// variant, the message from its `Display` (see
178    /// [`message`](Self::message)), the traceback from a
179    /// `CallbackError` or from the traceback mlua appends to a
180    /// `RuntimeError`.
181    pub fn from_mlua(e: &mlua::Error) -> Self {
182        match e {
183            mlua::Error::CallbackError { traceback, cause } => {
184                let (mut cause, mut traceback) = (cause, traceback);
185                while let mlua::Error::CallbackError {
186                    cause: inner,
187                    traceback: inner_tb,
188                } = &**cause
189                {
190                    cause = inner;
191                    traceback = inner_tb;
192                }
193                // The innermost cause, built the same way (so a
194                // `RuntimeError` cause has its traceback split off).
195                let inner = Self::from_mlua(cause);
196                let mut f = Self::new(LuaErrorKind::Callback, inner.message);
197                f.traceback = Some(traceback.clone())
198                    .filter(|t| !t.is_empty())
199                    .or(inner.traceback);
200                f
201            }
202            mlua::Error::WithContext { context, cause } => {
203                let mut f = Self::from_mlua(cause);
204                f.message = format!("{context}\n{}", f.message);
205                f
206            }
207            mlua::Error::RuntimeError(msg) => {
208                let (message, traceback) = split_traceback(msg);
209                let mut f = Self::new(LuaErrorKind::Runtime, message);
210                f.traceback = traceback;
211                f
212            }
213            mlua::Error::SyntaxError { message, .. } => {
214                Self::new(LuaErrorKind::Syntax, message.clone())
215            }
216            mlua::Error::MemoryError(msg) => Self::new(LuaErrorKind::Memory, msg.clone()),
217            mlua::Error::ExternalError(_) => Self::new(LuaErrorKind::External, e.to_string()),
218            mlua::Error::FromLuaConversionError { .. } | mlua::Error::BadArgument { .. } => {
219                Self::new(LuaErrorKind::Conversion, e.to_string())
220            }
221            #[cfg(feature = "serde")]
222            mlua::Error::SerializeError(_) | mlua::Error::DeserializeError(_) => {
223                Self::new(LuaErrorKind::Conversion, e.to_string())
224            }
225            _ => Self::new(LuaErrorKind::Other, e.to_string()),
226        }
227    }
228}
229
230impl fmt::Display for LuaFailure {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        f.write_str(&self.message)
233    }
234}
235
236impl From<mlua::Error> for LuaFailure {
237    fn from(e: mlua::Error) -> Self {
238        Self::from_mlua(&e)
239    }
240}
241
242/// Split the traceback mlua appends to a `RuntimeError` message.
243fn split_traceback(msg: &str) -> (String, Option<String>) {
244    match msg.find("\nstack traceback:") {
245        Some(pos) => (msg[..pos].to_string(), Some(msg[pos + 1..].to_string())),
246        None => (msg.to_string(), None),
247    }
248}
249
250/// The error a cancellation raises in Lua.
251///
252/// The cancel hook and [`cancellable`](crate::runtime::cancellable) raise
253/// `mlua::Error::external(Cancelled)`.  Rust recognises it by value, with
254/// [`mlua::Error::downcast_ref`], which walks the `CallbackError` /
255/// `WithContext` / `BadArgument` chain down to the `ExternalError`:
256///
257/// ```rust
258/// use mlua_isle::Cancelled;
259///
260/// fn is_cancel(e: &mlua::Error) -> bool {
261///     e.downcast_ref::<Cancelled>().is_some()
262/// }
263/// assert!(is_cancel(&mlua::Error::external(Cancelled)));
264/// assert!(!is_cancel(&mlua::Error::runtime("cancelled")));
265/// ```
266///
267/// Lua code sees it as an error value (a userdata whose `tostring` is
268/// `cancelled` plus a traceback); the `task` library's
269/// `task.is_cancelled(err)` is true for it (see [the `task` library](crate::runtime#the-task-library)).
270/// A host function that wants to report a cancel it observed itself can
271/// return `Err(mlua::Error::external(Cancelled))`.
272#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
273pub struct Cancelled;
274
275impl fmt::Display for Cancelled {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        f.write_str("cancelled")
278    }
279}
280
281impl std::error::Error for Cancelled {}
282
283/// Whether `e` is (or wraps) the cancellation error: [`Cancelled`], or
284/// an [`IsleError::Cancelled`] passed through `mlua::Error::external`.
285pub(crate) fn is_cancel(e: &mlua::Error) -> bool {
286    e.downcast_ref::<Cancelled>().is_some()
287        || matches!(e.downcast_ref::<IsleError>(), Some(IsleError::Cancelled))
288}
289
290/// The cancellation error, as raised into Lua.
291pub(crate) fn cancel_error() -> mlua::Error {
292    mlua::Error::external(Cancelled)
293}
294
295impl From<mlua::Error> for IsleError {
296    /// [`IsleError::Cancelled`] when `e` wraps [`Cancelled`] (found by
297    /// downcast, never by message), else [`IsleError::Lua`].
298    fn from(e: mlua::Error) -> Self {
299        if is_cancel(&e) {
300            Self::Cancelled
301        } else {
302            Self::Lua(LuaFailure::from_mlua(&e))
303        }
304    }
305}
306
307impl From<IsleError> for mlua::Error {
308    /// Lets `?` pass an `IsleError` out of a closure or host function that
309    /// returns `mlua::Result` (an init closure, a `create_function` /
310    /// `create_async_function` body).
311    ///
312    /// [`IsleError::Cancelled`] becomes `mlua::Error::external(`[`Cancelled`]`)`,
313    /// the same value the cancel hook raises, so a cancel stays a cancel
314    /// across the boundary: `task.is_cancelled(err)` is true for it in
315    /// Lua, and `IsleError::from` turns it back into
316    /// `IsleError::Cancelled`.  Every other variant becomes
317    /// `mlua::Error::external(e)`; brought back to Rust it is
318    /// `IsleError::Lua(f)` with `f.message` = `e.to_string()`, and
319    /// `f.kind` = [`LuaErrorKind::Callback`] when it came out of a host
320    /// function called from Lua ([`LuaErrorKind::External`] when it
321    /// did not cross a Lua call, e.g. from an init closure, which gives
322    /// `IsleError::Init`).
323    fn from(e: IsleError) -> Self {
324        match e {
325            IsleError::Cancelled => cancel_error(),
326            e => mlua::Error::external(e),
327        }
328    }
329}
330
331/// The message of a panic payload, when it is a `&str` or a `String`.
332pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> Option<String> {
333    payload
334        .downcast_ref::<&str>()
335        .map(|s| s.to_string())
336        .or_else(|| payload.downcast_ref::<String>().cloned())
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    fn assert_send_sync<T: Send + Sync + 'static>() {}
344
345    #[test]
346    fn error_types_are_send_sync() {
347        assert_send_sync::<IsleError>();
348        assert_send_sync::<LuaFailure>();
349        assert_send_sync::<Cancelled>();
350    }
351
352    #[test]
353    // `CallbackError::cause` is an `Arc<mlua::Error>`, which is not
354    // `Send` without mlua's `error-send` feature.
355    #[allow(clippy::arc_with_non_send_sync)]
356    fn cancel_is_found_through_callback_error() {
357        let wrapped = mlua::Error::CallbackError {
358            traceback: String::new(),
359            cause: std::sync::Arc::new(cancel_error()),
360        };
361        assert!(matches!(IsleError::from(wrapped), IsleError::Cancelled));
362        assert!(matches!(
363            IsleError::from(mlua::Error::runtime("__isle_cancelled__")),
364            IsleError::Lua(_)
365        ));
366    }
367
368    #[test]
369    #[allow(clippy::arc_with_non_send_sync)]
370    fn nested_messages_carry_no_traceback() {
371        let inner = mlua::Error::runtime("x:1: boom\nstack traceback:\n\t[C]: in ?");
372        let cb = mlua::Error::CallbackError {
373            traceback: "stack traceback:\n\t[C]: in f".into(),
374            cause: std::sync::Arc::new(inner.clone()),
375        };
376        let f = LuaFailure::from_mlua(&cb);
377        assert_eq!(f.kind, LuaErrorKind::Callback);
378        assert_eq!(f.message, "x:1: boom");
379        assert_eq!(
380            f.traceback.as_deref(),
381            Some("stack traceback:\n\t[C]: in f")
382        );
383
384        let ctx = mlua::Error::WithContext {
385            context: "while loading".into(),
386            cause: std::sync::Arc::new(inner),
387        };
388        let f = LuaFailure::from_mlua(&ctx);
389        assert_eq!(f.kind, LuaErrorKind::Runtime);
390        assert_eq!(f.message, "while loading\nx:1: boom");
391        assert!(f.traceback.is_some());
392    }
393
394    #[test]
395    fn runtime_error_traceback_is_split() {
396        let f = LuaFailure::from_mlua(&mlua::Error::runtime(
397            "x:1: boom\nstack traceback:\n\t[C]: in ?",
398        ));
399        assert_eq!(f.kind, LuaErrorKind::Runtime);
400        assert_eq!(f.message, "x:1: boom");
401        assert_eq!(
402            f.traceback.as_deref(),
403            Some("stack traceback:\n\t[C]: in ?")
404        );
405    }
406}