use std::error::Error;
use std::fmt::{
Display,
Formatter,
Result,
};
#[ derive( Debug ) ]
pub struct ParsingError<ExternalErrorType>
where
ExternalErrorType: Display + Error {
line: usize,
keyword: ParsingErrorType<ExternalErrorType>
}
impl<ExternalErrorType> ParsingError<ExternalErrorType>
where
ExternalErrorType: Display + Error {
pub fn new(
line: usize,
keyword: ParsingErrorType<ExternalErrorType>
) -> ParsingError<ExternalErrorType> {
ParsingError {
line,
keyword
}
}
}
impl<ExternalErrorType> Error for ParsingError<ExternalErrorType>
where
ExternalErrorType: Display + Error + 'static {
fn source( &self ) -> Option< &( dyn Error + 'static ) > {
if let ParsingErrorType::External( external_error ) = &self.keyword {
Some( external_error )
} else {
None
}
}
}
impl<ExternalErrorType> Display for ParsingError<ExternalErrorType>
where
ExternalErrorType: Display + Error {
fn fmt( &self, f: &mut Formatter<'_> ) -> Result {
write!( f,
"Error in line {}: {}",
self.line + 1,
self.keyword,
)
}
}
#[ derive( Debug ) ]
pub enum ParsingErrorType<ExternalErrorType>
where
ExternalErrorType: Display + Error {
BothBraketsInLine,
IsolatedClosingBraket,
MissingColon,
UnknownKeyword( String ),
MissingChild( String ),
FailedParsingValue,
External( ExternalErrorType ),
}
impl<ExternalErrorType> Display for ParsingErrorType<ExternalErrorType>
where
ExternalErrorType: Display + Error {
fn fmt( &self, f: &mut Formatter<'_> ) -> Result {
if let ParsingErrorType::External( custom_error ) = self {
Display::fmt( custom_error, f )?
}
write!( f, "{}",
match self {
ParsingErrorType::BothBraketsInLine =>
"Only an opening or a closing braket is allowed in a single line."
.to_owned(),
ParsingErrorType::IsolatedClosingBraket =>
"Found an orphaned closing braket, for which no opening braket exists."
.to_owned(),
ParsingErrorType::MissingColon =>
"A colon between the keyword and value is missing."
.to_owned(),
ParsingErrorType::UnknownKeyword( keyword ) =>
format!(
"Unknown keyword: \"{}\"",
keyword,
),
ParsingErrorType::MissingChild( keyword ) =>
format!(
"The keyword \"{}\" is missing.",
keyword,
),
ParsingErrorType::FailedParsingValue =>
"Failed to parse the given value."
.to_owned(),
ParsingErrorType::External( _ ) =>
"".to_owned(),
}
)
}
}