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