use std::fmt;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
Missing {
name: String,
},
Parse {
name: String,
raw: String,
message: String,
},
Validation {
errors: Vec<ValidationError>,
},
NotFound {
name: String,
},
Multiple {
errors: Vec<Error>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
pub name: String,
pub message: String,
pub hint: Option<String>,
}
impl Error {
pub fn missing(name: impl Into<String>) -> Self {
Self {
kind: ErrorKind::Missing { name: name.into() },
}
}
pub fn parse(
name: impl Into<String>,
raw: impl Into<String>,
message: impl Into<String>,
) -> Self {
Self {
kind: ErrorKind::Parse {
name: name.into(),
raw: raw.into(),
message: message.into(),
},
}
}
#[must_use]
pub fn validation(errors: Vec<ValidationError>) -> Self {
assert!(!errors.is_empty(), "validation errors must not be empty");
Self {
kind: ErrorKind::Validation { errors },
}
}
#[must_use]
pub fn validation_one(error: ValidationError) -> Self {
Self {
kind: ErrorKind::Validation {
errors: vec![error],
},
}
}
pub fn not_found(name: impl Into<String>) -> Self {
Self {
kind: ErrorKind::NotFound { name: name.into() },
}
}
#[must_use]
pub const fn kind(&self) -> &ErrorKind {
&self.kind
}
#[must_use]
pub fn into_kind(self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn multiple(errors: Vec<Self>) -> Self {
assert!(!errors.is_empty(), "errors must not be empty");
Self {
kind: ErrorKind::Multiple { errors },
}
}
}
impl ValidationError {
pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
Self {
name: name.into(),
message: message.into(),
hint: None,
}
}
#[must_use]
pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
self.hint = Some(hint.into());
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
ErrorKind::Missing { name } => {
write!(f, "environment variable '{name}' is required but not set")
}
ErrorKind::Parse { name, raw, message } => {
write!(f, "failed to parse '{name}': {message} (received: {raw:?})")
}
ErrorKind::Validation { errors } => {
let count = errors.len();
writeln!(
f,
"environment configuration failed ({count} error{})",
if count == 1 { "" } else { "s" },
)?;
for (i, ve) in errors.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
writeln!(f, " ┌─ {}", ve.name)?;
writeln!(f, " │")?;
writeln!(f, " │ {}", ve.message)?;
if let Some(hint) = &ve.hint {
writeln!(f, " │ hint: {hint}")?;
}
}
Ok(())
}
ErrorKind::Multiple { errors } => {
let count = errors.len();
writeln!(
f,
"environment configuration failed ({count} error{})",
if count == 1 { "" } else { "s" },
)?;
for (i, e) in errors.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
for line in e.to_string().lines() {
writeln!(f, " {line}")?;
}
}
Ok(())
}
ErrorKind::NotFound { name } => {
write!(
f,
"variable '{name}' was not declared in this configuration"
)
}
}
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.name, self.message)?;
if let Some(hint) = &self.hint {
write!(f, " (hint: {hint})")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
impl std::error::Error for ValidationError {}
impl From<ValidationError> for Error {
fn from(ve: ValidationError) -> Self {
Self::validation_one(ve)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_display() {
let err = Error::missing("APP_PORT");
assert_eq!(
err.to_string(),
"environment variable 'APP_PORT' is required but not set"
);
}
#[test]
fn parse_display() {
let err = Error::parse("APP_PORT", "abc", "invalid digit");
assert_eq!(
err.to_string(),
"failed to parse 'APP_PORT': invalid digit (received: \"abc\")"
);
}
#[test]
fn single_validation_display() {
let err = Error::validation_one(
ValidationError::new("APP_PORT", "must be 1–65535").with_hint("check your .env file"),
);
let text = err.to_string();
assert!(text.contains("1 error"));
assert!(text.contains("APP_PORT"));
assert!(text.contains("must be 1–65535"));
assert!(text.contains("hint: check your .env file"));
}
#[test]
fn multi_validation_display() {
let err = Error::validation(vec![
ValidationError::new("APP_PORT", "must be 1–65535"),
ValidationError::new("APP_DATABASE_URL", "required but not set")
.with_hint("set APP_DATABASE_URL"),
]);
let text = err.to_string();
assert!(text.contains("2 errors"));
assert!(text.contains("APP_PORT"));
assert!(text.contains("APP_DATABASE_URL"));
assert!(text.contains("hint: set APP_DATABASE_URL"));
}
#[test]
fn not_found_display() {
let err = Error::not_found("APP_MISSING");
assert_eq!(
err.to_string(),
"variable 'APP_MISSING' was not declared in this configuration"
);
}
#[test]
fn kind_roundtrip() {
let err = Error::missing("X");
assert!(matches!(err.kind(), ErrorKind::Missing { name } if name == "X"));
let kind = err.into_kind();
assert!(matches!(kind, ErrorKind::Missing { .. }));
}
#[test]
fn from_validation_error() {
let ve = ValidationError::new("X", "bad");
let err: Error = ve.into();
assert!(matches!(err.kind(), ErrorKind::Validation { errors } if errors.len() == 1));
}
#[test]
fn validation_error_display() {
let ve = ValidationError::new("X", "bad").with_hint("fix it");
assert_eq!(ve.to_string(), "X: bad (hint: fix it)");
let ve2 = ValidationError::new("Y", "worse");
assert_eq!(ve2.to_string(), "Y: worse");
}
#[test]
#[should_panic(expected = "validation errors must not be empty")]
fn empty_validation_panics() {
let _ = Error::validation(vec![]);
}
#[test]
fn error_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Error>();
assert_send_sync::<ValidationError>();
}
#[test]
fn multiple_display() {
let err = Error::multiple(vec![
Error::missing("APP_PORT"),
Error::parse("APP_TIMEOUT", "abc", "invalid digit"),
]);
let text = err.to_string();
assert!(text.contains("2 errors"), "message: {text}");
assert!(text.contains("APP_PORT"), "message: {text}");
assert!(text.contains("APP_TIMEOUT"), "message: {text}");
}
}