Skip to content

Commit

Permalink
feat: Ability to "wrap" other errors inside ObjectError.
Browse files Browse the repository at this point in the history
  • Loading branch information
andoriyu committed Mar 22, 2020
1 parent 5f1cff2 commit 7e4db2c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ mod test {
use crate::raw::object::Object;
use crate::raw::parser::Parser;
use libucl_bind::ucl_type_t;
use std::error::Error;
use std::path::Display;

#[test]
fn string_parsing() {
Expand Down Expand Up @@ -190,4 +192,12 @@ mod test {
assert_eq!(ucl_type_t::UCL_STRING, obj_str.kind());
assert_eq!("a string without null", obj_str.as_string().unwrap());
}

#[test]
fn dyn_error() {
let err = std::io::Error::from_raw_os_error(42);
let err = ObjectError::other(err);

assert!(err.to_string().contains("os error 42"));
}
}
16 changes: 15 additions & 1 deletion src/raw/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::raw::{utils, Priority};
use crate::traits::FromObject;
use bitflags::_core::borrow::Borrow;
use bitflags::_core::convert::Infallible;
use bitflags::_core::fmt::Formatter;
use bitflags::_core::fmt::{Formatter, Display};
use libucl_bind::{
ucl_object_frombool, ucl_object_fromdouble, ucl_object_fromint, ucl_object_fromstring,
ucl_object_get_priority, ucl_object_key, ucl_object_lookup, ucl_object_lookup_path,
Expand Down Expand Up @@ -42,16 +42,29 @@ pub enum ObjectError {
IntConversionError(TryFromIntError),
/// Wrapper around `AddrParseError`.
AddrParseError(AddrParseError),
/// An error that we couldn't match to internal type.
Other(String),
/// Not an error, but required for some conversions.
None,
}

impl Error for ObjectError {}

impl ObjectError {
/// Wrap error in Box<>.
pub fn boxed(self) -> Box<ObjectError> {
Box::new(self)
}

/// Wrap error in Box<> and erase its type.
pub fn boxed_dyn(self) -> Box<dyn Error> {
Box::new(self)
}

/// Create a new error `Other` by extracting the error description.
pub fn other<E: Error + Display>(err: E) -> ObjectError {
ObjectError::Other(err.to_string())
}
}
impl From<Infallible> for ObjectError {
fn from(_: Infallible) -> Self {
Expand Down Expand Up @@ -85,6 +98,7 @@ impl fmt::Display for ObjectError {
),
ObjectError::IntConversionError(e) => e.fmt(f),
ObjectError::AddrParseError(e) => e.fmt(f),
ObjectError::Other(e) => e.fmt(f),
ObjectError::None => write!(f, "Impossible error was possible after all."),
}
}
Expand Down

0 comments on commit 7e4db2c

Please sign in to comment.