mlua/error.rs
1//! Lua error handling.
2//!
3//! This module provides the [`Error`] type returned by all fallible `mlua` operations, together
4//! with extension traits for adapting Rust errors for use within Lua.
5
6use std::error::Error as StdError;
7use std::fmt;
8use std::io::Error as IoError;
9use std::net::AddrParseError;
10use std::result::Result as StdResult;
11use std::str::Utf8Error;
12use std::sync::Arc;
13
14use crate::private::Sealed;
15
16#[cfg(feature = "error-send")]
17type DynStdError = dyn StdError + Send + Sync;
18
19#[cfg(not(feature = "error-send"))]
20type DynStdError = dyn StdError;
21
22/// Error type returned by `mlua` methods.
23#[derive(Debug, Clone)]
24#[non_exhaustive]
25pub enum Error {
26 /// Syntax error while parsing Lua source code.
27 SyntaxError {
28 /// The error message as returned by Lua.
29 message: String,
30 /// `true` if the error can likely be fixed by appending more input to the source code.
31 ///
32 /// This is useful for implementing REPLs as they can query the user for more input if this
33 /// is set.
34 incomplete_input: bool,
35 },
36 /// Lua runtime error, aka `LUA_ERRRUN`.
37 ///
38 /// The Lua VM returns this error when a builtin operation is performed on incompatible types.
39 /// Among other things, this includes invoking operators on wrong types (such as calling or
40 /// indexing a `nil` value).
41 RuntimeError(String),
42 /// Lua memory error, aka `LUA_ERRMEM`
43 ///
44 /// The Lua VM returns this error when the allocator does not return the requested memory, aka
45 /// it is an out-of-memory error.
46 MemoryError(String),
47 /// Lua garbage collector error, aka `LUA_ERRGCMM`.
48 ///
49 /// The Lua VM returns this error when there is an error running a `__gc` metamethod.
50 #[cfg(any(feature = "lua53", feature = "lua52", doc))]
51 #[cfg_attr(docsrs, doc(cfg(any(feature = "lua53", feature = "lua52"))))]
52 GarbageCollectorError(String),
53 /// Potentially unsafe action in safe mode.
54 SafetyError(String),
55 /// Memory control is not available.
56 ///
57 /// This error can only happen when Lua state was not created by us and does not have the
58 /// custom allocator attached.
59 MemoryControlNotAvailable,
60 /// A mutable callback has triggered Lua code that has called the same mutable callback again.
61 ///
62 /// This is an error because a mutable callback can only be borrowed mutably once.
63 RecursiveMutCallback,
64 /// Either a callback or a userdata method has been called, but the callback or userdata has
65 /// been destructed.
66 ///
67 /// This can happen either due to to being destructed in a previous __gc, or due to being
68 /// destructed from exiting a `Lua::scope` call.
69 CallbackDestructed,
70 /// Not enough stack space to place arguments to Lua functions or return values from callbacks.
71 ///
72 /// Due to the way `mlua` works, it should not be directly possible to run out of stack space
73 /// during normal use. The only way that this error can be triggered is if a `Function` is
74 /// called with a huge number of arguments, or a Rust callback returns a huge number of return
75 /// values.
76 StackError,
77 /// Too many arguments to [`Function::bind`].
78 ///
79 /// [`Function::bind`]: crate::Function::bind
80 BindError,
81 /// Bad argument received from Lua (usually when calling a function).
82 ///
83 /// This error can help to identify the argument that caused the error
84 /// (which is stored in the corresponding field).
85 BadArgument {
86 /// Function that was called.
87 to: Option<String>,
88 /// Argument position (usually starts from 1).
89 pos: usize,
90 /// Argument name.
91 name: Option<String>,
92 /// Underlying error returned when converting argument to a Lua value.
93 cause: Arc<Error>,
94 },
95 /// A Lua value could not be converted to the expected Rust type.
96 FromLuaConversionError {
97 /// Name of the Lua type that could not be converted.
98 from: &'static str,
99 /// Name of the Rust type that could not be created.
100 to: String,
101 /// A string containing more detailed error information.
102 message: Option<String>,
103 },
104 /// [`Thread::resume`] was called on an unresumable coroutine.
105 ///
106 /// A coroutine is unresumable if its main function has returned or if an error has occurred
107 /// inside the coroutine. Already running coroutines are also marked as unresumable.
108 ///
109 /// [`Thread::status`] can be used to check if the coroutine can be resumed without causing this
110 /// error.
111 ///
112 /// [`Thread::resume`]: crate::Thread::resume
113 /// [`Thread::status`]: crate::Thread::status
114 CoroutineUnresumable,
115 /// An [`AnyUserData`] is not the expected type in a borrow.
116 ///
117 /// This error can only happen when manually using [`AnyUserData`], or when implementing
118 /// metamethods for binary operators. Refer to the documentation of [`UserDataMethods`] for
119 /// details.
120 ///
121 /// [`AnyUserData`]: crate::AnyUserData
122 /// [`UserDataMethods`]: crate::UserDataMethods
123 UserDataTypeMismatch,
124 /// An [`AnyUserData`] borrow failed because it has been destructed.
125 ///
126 /// This error can happen either due to to being destructed in a previous __gc, or due to being
127 /// destructed from exiting a `Lua::scope` call.
128 ///
129 /// [`AnyUserData`]: crate::AnyUserData
130 UserDataDestructed,
131 /// An [`AnyUserData`] immutable borrow failed.
132 ///
133 /// This error can occur when a method on a [`UserData`] type calls back into Lua, which then
134 /// tries to call a method on the same [`UserData`] type. Consider restructuring your API to
135 /// prevent these errors.
136 ///
137 /// [`AnyUserData`]: crate::AnyUserData
138 /// [`UserData`]: crate::UserData
139 UserDataBorrowError,
140 /// An [`AnyUserData`] mutable borrow failed.
141 ///
142 /// This error can occur when a method on a [`UserData`] type calls back into Lua, which then
143 /// tries to call a method on the same [`UserData`] type. Consider restructuring your API to
144 /// prevent these errors.
145 ///
146 /// [`AnyUserData`]: crate::AnyUserData
147 /// [`UserData`]: crate::UserData
148 UserDataBorrowMutError,
149 /// A [`MetaMethod`] operation is restricted (typically for `__gc` or `__metatable`).
150 ///
151 /// [`MetaMethod`]: crate::MetaMethod
152 MetaMethodRestricted(String),
153 /// A [`MetaMethod`] (eg. `__index` or `__newindex`) has invalid type.
154 ///
155 /// [`MetaMethod`]: crate::MetaMethod
156 MetaMethodTypeError {
157 /// Name of the metamethod.
158 method: String,
159 /// Passed value type.
160 type_name: &'static str,
161 /// A string containing more detailed error information.
162 message: Option<String>,
163 },
164 /// A [`RegistryKey`] produced from a different Lua state was used.
165 ///
166 /// [`RegistryKey`]: crate::RegistryKey
167 MismatchedRegistryKey,
168 /// A Rust callback returned `Err`, raising the contained `Error` as a Lua error.
169 CallbackError {
170 /// Lua call stack backtrace.
171 traceback: String,
172 /// Original error returned by the Rust code.
173 cause: Arc<Error>,
174 },
175 /// A Rust panic that was previously resumed, returned again.
176 ///
177 /// This error can occur only when a Rust panic resumed previously was recovered
178 /// and returned again.
179 PreviouslyResumedPanic,
180 /// Serialization error.
181 #[cfg(feature = "serde")]
182 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
183 SerializeError(String),
184 /// Deserialization error.
185 #[cfg(feature = "serde")]
186 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
187 DeserializeError(String),
188 /// A custom error.
189 ///
190 /// This can be used for returning user-defined errors from callbacks.
191 ///
192 /// Returning `Err(ExternalError(...))` from a Rust callback will raise the error as a Lua
193 /// error. The Rust code that originally invoked the Lua code then receives a `CallbackError`,
194 /// from which the original error (and a stack traceback) can be recovered.
195 ExternalError(Arc<DynStdError>),
196 /// An error with additional context.
197 WithContext {
198 /// A string containing additional context.
199 context: String,
200 /// Underlying error.
201 cause: Arc<Error>,
202 },
203}
204
205/// A specialized `Result` type used by `mlua`'s API.
206pub type Result<T> = StdResult<T, Error>;
207
208#[cfg(not(tarpaulin_include))]
209impl fmt::Display for Error {
210 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
211 match self {
212 Error::SyntaxError { message, .. } => write!(fmt, "syntax error: {message}"),
213 Error::RuntimeError(msg) => write!(fmt, "runtime error: {msg}"),
214 Error::MemoryError(msg) => {
215 write!(fmt, "memory error: {msg}")
216 }
217 #[cfg(any(feature = "lua53", feature = "lua52"))]
218 Error::GarbageCollectorError(msg) => {
219 write!(fmt, "garbage collector error: {msg}")
220 }
221 Error::SafetyError(msg) => {
222 write!(fmt, "safety error: {msg}")
223 }
224 Error::MemoryControlNotAvailable => {
225 write!(fmt, "memory control is not available")
226 }
227 Error::RecursiveMutCallback => write!(fmt, "mutable callback called recursively"),
228 Error::CallbackDestructed => write!(
229 fmt,
230 "a destructed callback or destructed userdata method was called"
231 ),
232 Error::StackError => write!(
233 fmt,
234 "out of Lua stack, too many arguments to a Lua function or too many return values from a callback"
235 ),
236 Error::BindError => write!(fmt, "too many arguments to Function::bind"),
237 Error::BadArgument { to, pos, name, cause } => {
238 if let Some(name) = name {
239 write!(fmt, "bad argument `{name}`")?;
240 } else {
241 write!(fmt, "bad argument #{pos}")?;
242 }
243 if let Some(to) = to {
244 write!(fmt, " to `{to}`")?;
245 }
246 write!(fmt, ": {cause}")
247 }
248 Error::FromLuaConversionError { from, to, message } => {
249 write!(fmt, "error converting Lua {from} to {to}")?;
250 match message {
251 None => Ok(()),
252 Some(message) => write!(fmt, " ({message})"),
253 }
254 }
255 Error::CoroutineUnresumable => write!(fmt, "coroutine is non-resumable"),
256 Error::UserDataTypeMismatch => write!(fmt, "userdata is not expected type"),
257 Error::UserDataDestructed => write!(fmt, "userdata has been destructed"),
258 Error::UserDataBorrowError => write!(fmt, "error borrowing userdata"),
259 Error::UserDataBorrowMutError => write!(fmt, "error mutably borrowing userdata"),
260 Error::MetaMethodRestricted(method) => write!(fmt, "metamethod {method} is restricted"),
261 Error::MetaMethodTypeError {
262 method,
263 type_name,
264 message,
265 } => {
266 write!(fmt, "metamethod {method} has unsupported type {type_name}")?;
267 match message {
268 None => Ok(()),
269 Some(message) => write!(fmt, " ({message})"),
270 }
271 }
272 Error::MismatchedRegistryKey => {
273 write!(fmt, "RegistryKey used from different Lua state")
274 }
275 Error::CallbackError { cause, traceback } => {
276 // Trace errors down to the root
277 let (mut cause, mut full_traceback) = (cause, None);
278 while let Error::CallbackError {
279 cause: cause2,
280 traceback: traceback2,
281 } = &**cause
282 {
283 cause = cause2;
284 full_traceback = Some(traceback2);
285 }
286 writeln!(fmt, "{cause}")?;
287 if let Some(full_traceback) = full_traceback {
288 let traceback = traceback.trim_start_matches("stack traceback:");
289 let traceback = traceback.trim_start().trim_end();
290 // Try to find local traceback within the full traceback
291 if let Some(pos) = full_traceback.find(traceback) {
292 write!(fmt, "{}", &full_traceback[..pos])?;
293 writeln!(fmt, ">{}", &full_traceback[pos..].trim_end())?;
294 } else {
295 writeln!(fmt, "{}", full_traceback.trim_end())?;
296 }
297 } else {
298 writeln!(fmt, "{}", traceback.trim_end())?;
299 }
300 Ok(())
301 }
302 Error::PreviouslyResumedPanic => {
303 write!(fmt, "previously resumed panic returned again")
304 }
305 #[cfg(feature = "serde")]
306 Error::SerializeError(err) => {
307 write!(fmt, "serialize error: {err}")
308 }
309 #[cfg(feature = "serde")]
310 Error::DeserializeError(err) => {
311 write!(fmt, "deserialize error: {err}")
312 }
313 Error::ExternalError(err) => err.fmt(fmt),
314 Error::WithContext { context, cause } => {
315 writeln!(fmt, "{context}")?;
316 write!(fmt, "{cause}")
317 }
318 }
319 }
320}
321
322impl StdError for Error {
323 fn source(&self) -> Option<&(dyn StdError + 'static)> {
324 match self {
325 // An error type with a source error should either return that error via source or
326 // include that source's error message in its own Display output, but never both.
327 // https://blog.rust-lang.org/inside-rust/2021/07/01/What-the-error-handling-project-group-is-working-towards.html
328 // Given that we include source to fmt::Display implementation for `CallbackError`, this call
329 // returns nothing.
330 Error::CallbackError { .. } => None,
331 Error::ExternalError(err) => err.source(),
332 Error::WithContext { cause, .. } => Self::source(cause),
333 _ => None,
334 }
335 }
336}
337
338impl Error {
339 /// Creates a new `RuntimeError` with the given message.
340 #[inline]
341 pub fn runtime<S: fmt::Display>(message: S) -> Self {
342 Error::RuntimeError(message.to_string())
343 }
344
345 /// Wraps an external error object.
346 #[inline]
347 pub fn external<T: Into<Box<DynStdError>>>(err: T) -> Self {
348 let boxed = err.into();
349 match boxed.downcast::<Self>() {
350 Ok(err) => *err,
351 Err(boxed) => Error::ExternalError(boxed.into()),
352 }
353 }
354
355 /// Attempts to downcast the external error object to a concrete type by reference.
356 pub fn downcast_ref<T>(&self) -> Option<&T>
357 where
358 T: StdError + 'static,
359 {
360 match self {
361 Error::ExternalError(err) => err.downcast_ref(),
362 Error::WithContext { cause, .. } => Self::downcast_ref(cause),
363 _ => None,
364 }
365 }
366
367 /// An iterator over the chain of nested errors wrapped by this Error.
368 pub fn chain(&self) -> impl Iterator<Item = &(dyn StdError + 'static)> {
369 Chain {
370 root: self,
371 current: None,
372 }
373 }
374
375 /// Returns the parent of this error.
376 #[doc(hidden)]
377 pub fn parent(&self) -> Option<&Error> {
378 match self {
379 Error::CallbackError { cause, .. } => Some(cause.as_ref()),
380 Error::WithContext { cause, .. } => Some(cause.as_ref()),
381 _ => None,
382 }
383 }
384
385 pub(crate) fn bad_self_argument(to: &str, cause: Error) -> Self {
386 Error::BadArgument {
387 to: Some(to.to_string()),
388 pos: 1,
389 name: Some("self".to_string()),
390 cause: Arc::new(cause),
391 }
392 }
393
394 #[inline]
395 pub(crate) fn from_lua_conversion(
396 from: &'static str,
397 to: impl ToString,
398 message: impl Into<Option<String>>,
399 ) -> Self {
400 Error::FromLuaConversionError {
401 from,
402 to: to.to_string(),
403 message: message.into(),
404 }
405 }
406}
407
408/// Trait for converting [`std::error::Error`] into Lua [`Error`].
409pub trait ExternalError {
410 fn into_lua_err(self) -> Error;
411}
412
413impl<E: Into<Box<DynStdError>>> ExternalError for E {
414 fn into_lua_err(self) -> Error {
415 Error::external(self)
416 }
417}
418
419/// Trait for converting [`std::result::Result`] into Lua [`Result`].
420pub trait ExternalResult<T> {
421 fn into_lua_err(self) -> Result<T>;
422}
423
424impl<T, E> ExternalResult<T> for StdResult<T, E>
425where
426 E: ExternalError,
427{
428 fn into_lua_err(self) -> Result<T> {
429 self.map_err(|e| e.into_lua_err())
430 }
431}
432
433/// Provides the `context` method for [`Error`] and `Result<T, Error>`.
434pub trait ErrorContext: Sealed {
435 /// Wraps the error value with additional context.
436 fn context<C: fmt::Display>(self, context: C) -> Self;
437
438 /// Wrap the error value with additional context that is evaluated lazily
439 /// only once an error does occur.
440 fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self;
441}
442
443impl ErrorContext for Error {
444 fn context<C: fmt::Display>(self, context: C) -> Self {
445 let context = context.to_string();
446 match self {
447 Error::WithContext { cause, .. } => Error::WithContext { context, cause },
448 _ => Error::WithContext {
449 context,
450 cause: Arc::new(self),
451 },
452 }
453 }
454
455 fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self {
456 let context = f(&self).to_string();
457 match self {
458 Error::WithContext { cause, .. } => Error::WithContext { context, cause },
459 _ => Error::WithContext {
460 context,
461 cause: Arc::new(self),
462 },
463 }
464 }
465}
466
467impl<T> ErrorContext for Result<T> {
468 fn context<C: fmt::Display>(self, context: C) -> Self {
469 self.map_err(|err| err.context(context))
470 }
471
472 fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self {
473 self.map_err(|err| err.with_context(f))
474 }
475}
476
477impl From<AddrParseError> for Error {
478 fn from(err: AddrParseError) -> Self {
479 Error::external(err)
480 }
481}
482
483impl From<IoError> for Error {
484 fn from(err: IoError) -> Self {
485 Error::external(err)
486 }
487}
488
489impl From<Utf8Error> for Error {
490 fn from(err: Utf8Error) -> Self {
491 Error::external(err)
492 }
493}
494
495#[cfg(feature = "serde")]
496impl serde::ser::Error for Error {
497 fn custom<T: fmt::Display>(msg: T) -> Self {
498 Self::SerializeError(msg.to_string())
499 }
500}
501
502#[cfg(feature = "serde")]
503impl serde::de::Error for Error {
504 fn custom<T: fmt::Display>(msg: T) -> Self {
505 Self::DeserializeError(msg.to_string())
506 }
507}
508
509#[cfg(feature = "anyhow")]
510impl From<anyhow::Error> for Error {
511 fn from(err: anyhow::Error) -> Self {
512 match err.downcast::<Self>() {
513 Ok(err) => err,
514 Err(err) => Error::external(err),
515 }
516 }
517}
518
519struct Chain<'a> {
520 root: &'a Error,
521 current: Option<&'a (dyn StdError + 'static)>,
522}
523
524impl<'a> Iterator for Chain<'a> {
525 type Item = &'a (dyn StdError + 'static);
526
527 fn next(&mut self) -> Option<Self::Item> {
528 loop {
529 let error: Option<&dyn StdError> = match self.current {
530 None => {
531 self.current = Some(self.root);
532 self.current
533 }
534 Some(current) => match current.downcast_ref::<Error>()? {
535 Error::BadArgument { cause, .. }
536 | Error::CallbackError { cause, .. }
537 | Error::WithContext { cause, .. } => {
538 self.current = Some(&**cause);
539 self.current
540 }
541 Error::ExternalError(err) => {
542 self.current = Some(&**err);
543 self.current
544 }
545 _ => None,
546 },
547 };
548
549 // Skip `ExternalError` as it only wraps the underlying error
550 // without meaningful context
551 if let Some(Error::ExternalError(_)) = error?.downcast_ref::<Error>() {
552 continue;
553 }
554
555 return self.current;
556 }
557 }
558}
559
560#[cfg(test)]
561mod assertions {
562 #[cfg(not(feature = "error-send"))]
563 static_assertions::assert_not_impl_any!(super::Error: Send, Sync);
564 #[cfg(feature = "send")]
565 static_assertions::assert_impl_all!(super::Error: Send, Sync);
566}