bind-conf/dns_zone/src/error.rs

98 lines
3.1 KiB
Rust

use crate::context::Context;
use crate::parser::ParseError;
use std::fmt::{self, Display};
pub type Result<T> = std::result::Result<T, Error<ErrorType>>;
#[derive(Debug, PartialEq)]
pub enum ErrorType {
ParseError(ParseError),
Eof,
ExpectedWord,
ExpectedCharacter(char),
ExpectedCharacterString,
UnexpectedClosingBraket,
NoTtl,
NoOwner,
NoClass,
NoRecordType,
NoRecord,
BadParameter,
UnknownControlEntry,
// Name related Error
EmptyLabel,
LabelTooLong,
NonAsciiChar,
BadEscape,
InvalidDomain,
InvalidMailbox,
InvalidHostname,
}
impl Display for ErrorType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ErrorType::ParseError(ref err) => err.fmt(f),
ErrorType::Eof => write!(f, "unexpected end of file"),
ErrorType::ExpectedWord => write!(f, "expected a word"),
ErrorType::ExpectedCharacter(ch) => write!(f, "expected character `{:?}`", ch),
ErrorType::ExpectedCharacterString => write!(f, "expected a character string"),
ErrorType::UnexpectedClosingBraket => write!(f, "unexpected closing braket"),
ErrorType::NoTtl => write!(f, "no ttl"),
ErrorType::NoOwner => write!(f, "no owner"),
ErrorType::NoClass => write!(f, "no class"),
ErrorType::NoRecordType => write!(f, "no record type"),
ErrorType::NoRecord => write!(f, "no record"),
ErrorType::BadParameter => write!(f, "bad parameter"),
ErrorType::UnknownControlEntry => write!(f, "unknown control entry"),
ErrorType::EmptyLabel => write!(f, "empty label"),
ErrorType::LabelTooLong => write!(f, "label too long"),
ErrorType::NonAsciiChar => write!(f, "non ascii char"),
ErrorType::BadEscape => write!(f, "bad escape"),
ErrorType::InvalidDomain => write!(f, "invalid domain"),
ErrorType::InvalidMailbox => write!(f, "invalid mailbox"),
ErrorType::InvalidHostname => write!(f, "invalid hostname"),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Error<T: Display + fmt::Debug + PartialEq> {
pub error_type: T,
pub message: Option<String>,
pub context: Context,
}
impl<T> Display for Error<T> where T: Display + fmt::Debug + PartialEq {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(message) = &self.message {
write!(f, "Error at [{}]: {}: {}", self.context, self.error_type, message)
} else {
write!(f, "Error at [{}]: {}", self.context, self.error_type)
}
}
}
impl<T> Error<T> where T: Display + fmt::Debug + PartialEq {
pub fn new(error_type: T, message: String, context: Context) -> Self {
Error {
error_type,
message: Some(message),
context
}
}
}
impl From<ErrorType> for Error<ErrorType> {
fn from(error_type: ErrorType) -> Self {
Error {
error_type,
message: None,
context: Context::default()
}
}
}