Add `Error::downcast_ref()` method
This commit is contained in:
parent
4bc6501d2e
commit
6a647f58be
18
src/error.rs
18
src/error.rs
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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),
|
||||
};
|
||||
|
||||
|
|
Loading…
Reference in New Issue