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