From 6a647f58befde15e7aa3a55729b1c5e5b77cf2aa Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Sun, 19 Mar 2023 00:22:51 +0000 Subject: [PATCH] Add `Error::downcast_ref()` method --- src/error.rs | 18 +++++++++++++++--- tests/chunk.rs | 5 ++--- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/error.rs b/src/error.rs index 7e74d69..233f130 100644 --- a/src/error.rs +++ b/src/error.rs @@ -336,10 +336,22 @@ impl StdError for Error { } impl Error { + /// Wraps an external error object. pub fn external>>(err: T) -> Self { Error::ExternalError(err.into().into()) } + /// Attempts to downcast the external error object to a concrete type by reference. + pub fn downcast_ref(&self) -> Option<&T> + where + T: StdError + 'static, + { + match self { + Error::ExternalError(err) => err.downcast_ref(), + _ => None, + } + } + pub(crate) fn bad_self_argument(to: &str, cause: Error) -> Self { Error::BadArgument { to: Some(to.to_string()), @@ -423,19 +435,19 @@ impl ErrorContext for StdResult { } } -impl std::convert::From for Error { +impl From for Error { fn from(err: AddrParseError) -> Self { Error::external(err) } } -impl std::convert::From for Error { +impl From for Error { fn from(err: IoError) -> Self { Error::external(err) } } -impl std::convert::From for Error { +impl From for Error { fn from(err: Utf8Error) -> Self { Error::external(err) } diff --git a/tests/chunk.rs b/tests/chunk.rs index 1a26c3c..b1638c7 100644 --- a/tests/chunk.rs +++ b/tests/chunk.rs @@ -1,7 +1,7 @@ use std::fs; use std::io; -use mlua::{Error, Lua, Result}; +use mlua::{Lua, Result}; #[test] fn test_chunk_path() -> Result<()> { @@ -18,8 +18,7 @@ fn test_chunk_path() -> Result<()> { assert_eq!(i, 321); match lua.load(&*temp_dir.path().join("module2.lua")).exec() { - Err(Error::ExternalError(err)) - if err.downcast_ref::().unwrap().kind() == io::ErrorKind::NotFound => {} + Err(err) if err.downcast_ref::().unwrap().kind() == io::ErrorKind::NotFound => {} res => panic!("expected io::Error, got {:?}", res), };