LINE1 10 20 30 40 50 60 70 80 901use std::error::Error;23#[derive(Debug)]4pub struct ContextError {5 context: String,6 source: Box<dyn Error + Send + Sync>,7 suggestion: Option<String>,8}910impl ContextError {11 pub fn new<E>(context: impl Into<String>, source: E) -> Self12 where13 E: Error + Send + Sync + 'static,14 {15 Self {16 context: context.into(),17 source: Box::new(source),18 suggestion: None,19 }20 }2122 pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {23 self.suggestion = Some(suggestion.into());24 self25 }2627 fn suggestion(&self) -> Option<&str> {28 self.suggestion.as_deref()29 }30}3132impl std::fmt::Display for ContextError {33 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {34 formatter.write_str(&self.context)35 }36}3738impl Error for ContextError {39 fn source(&self) -> Option<&(dyn Error + 'static)> {40 Some(self.source.as_ref())41 }42}4344pub fn format_cli_error(error: &(dyn Error + 'static)) -> String {45 let message = error.to_string();46 let mut lines = vec![format!("ino: {message}")];47 let mut previous = message;48 let mut source = error.source();49 while let Some(cause_error) = source {50 let cause = cause_error.to_string();51 if cause != previous {52 lines.push(format!(" Caused by: {cause}"));53 }54 previous = cause;55 source = cause_error.source();56 }5758 let mut current = Some(error);59 while let Some(cause) = current {60 if let Some(context) = cause.downcast_ref::<ContextError>()61 && let Some(suggestion) = context.suggestion()62 {63 lines.push(format!(" Try: {suggestion}"));64 break;65 }66 current = cause.source();67 }6869 lines.join("\n")70}7172#[cfg(test)]73mod tests {74 use std::error::Error;7576 use super::{ContextError, format_cli_error};7778 #[test]79 fn context_error_formats_context_cause_and_suggestion() {80 let error = ContextError::new(81 "starting self-update script `/tmp/missing.sh`",82 std::io::Error::new(83 std::io::ErrorKind::NotFound,84 "No such file or directory (os error 2)",85 ),86 )87 .with_suggestion("check that the script exists and is executable");8889 let formatted = format_cli_error(&error);9091 assert!(formatted.starts_with("ino: starting self-update script `/tmp/missing.sh`"));92 assert!(formatted.contains("Caused by: No such file or directory"));93 assert!(formatted.ends_with("Try: check that the script exists and is executable"));94 }9596 #[test]97 fn context_error_exposes_its_source() {98 let error = ContextError::new(99 "opening a file",100 std::io::Error::new(101 std::io::ErrorKind::NotFound,102 "No such file or directory (os error 2)",103 ),104 );105106 assert_eq!(107 error108 .source()109 .and_then(|source| source.downcast_ref::<std::io::Error>())110 .map(std::io::Error::kind),111 Some(std::io::ErrorKind::NotFound)112 );113 }114}