Skip to content

Commit d6784a7

Browse files
committed
Update Error::downcast_ref to follow Error::chain
`Error::downcast_ref` now descends through `BadArgument` and `CallbackError`, matching `chain` traversal logic
1 parent d904423 commit d6784a7

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

src/error.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,9 @@ impl Error {
359359
{
360360
match self {
361361
Error::ExternalError(err) => err.downcast_ref(),
362-
Error::WithContext { cause, .. } => Self::downcast_ref(cause),
362+
Error::BadArgument { cause, .. }
363+
| Error::CallbackError { cause, .. }
364+
| Error::WithContext { cause, .. } => Self::downcast_ref(cause),
363365
_ => None,
364366
}
365367
}

tests/error.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::error::Error as _;
2+
use std::sync::Arc;
23
use std::{fmt, io};
34

45
use mlua::{Error, ErrorContext, Lua, Result};
@@ -77,6 +78,31 @@ fn test_error_chain() -> Result<()> {
7778
Ok(())
7879
}
7980

81+
#[test]
82+
fn test_error_downcast() -> Result<()> {
83+
let lua = Lua::new();
84+
85+
let func = lua.create_function(|_, ()| Err::<(), _>(Error::external(io::Error::other("boom"))))?;
86+
let err = func.call::<()>(()).unwrap_err();
87+
assert!(matches!(err, Error::CallbackError { .. }));
88+
assert!(err.downcast_ref::<io::Error>().is_some());
89+
assert!(err.downcast_ref::<fmt::Error>().is_none());
90+
91+
let bad_arg = Error::BadArgument {
92+
to: Some("func".to_string()),
93+
pos: 1,
94+
name: Some("arg".to_string()),
95+
cause: Arc::new(Error::external(io::Error::new(
96+
io::ErrorKind::InvalidInput,
97+
"bad",
98+
))),
99+
};
100+
assert!(bad_arg.downcast_ref::<io::Error>().is_some());
101+
assert!(bad_arg.downcast_ref::<fmt::Error>().is_none());
102+
103+
Ok(())
104+
}
105+
80106
#[test]
81107
fn test_external_error() {
82108
// `Error::external` should preserve `mlua::Error`

0 commit comments

Comments
 (0)