Add `Error::downcast_ref()` method

This commit is contained in:
Alex Orlenko 2023-03-19 00:22:51 +00:00
parent 4bc6501d2e
commit 6a647f58be
No known key found for this signature in database
GPG Key ID: 4C150C250863B96D
2 changed files with 17 additions and 6 deletions

View File

@ -336,10 +336,22 @@ impl StdError for Error {
}
impl Error {
/// Wraps an external error object.
pub fn external<T: Into<Box<dyn StdError + Send + Sync>>>(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<T>(&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<T> ErrorContext for StdResult<T, Error> {
}
}
impl std::convert::From<AddrParseError> for Error {
impl From<AddrParseError> for Error {
fn from(err: AddrParseError) -> Self {
Error::external(err)
}
}
impl std::convert::From<IoError> for Error {
impl From<IoError> for Error {
fn from(err: IoError) -> Self {
Error::external(err)
}
}
impl std::convert::From<Utf8Error> for Error {
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Self {
Error::external(err)
}

View File

@ -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::<io::Error>().unwrap().kind() == io::ErrorKind::NotFound => {}
Err(err) if err.downcast_ref::<io::Error>().unwrap().kind() == io::ErrorKind::NotFound => {}
res => panic!("expected io::Error, got {:?}", res),
};