1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
//! # User Facing Error //! A library for conveniently displaying well-formatted, and good looking //! errors to users of CLI applications. Useful for bubbling up unrecoverable //! errors to inform the user what they can do to fix them. Error messages you'd //! be proud to show your mom. #![deny( missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unstable_features, unsafe_code, unused_import_braces, unused_qualifications )] // Standard Library Dependencies use core::fmt::{self, Debug, Display}; use std::error::Error; /************* * CONSTANTS * *************/ // 'Error:' with a red background and white, bold, text const SUMMARY_PREFIX: &str = "\u{001b}[97;41;22mError:\u{001b}[91;49;1m "; // ' - ' bullet point in yellow and text in bold white const REASON_PREFIX: &str = "\u{001b}[93;49;1m - \u{001b}[97;49;1m"; // Muted white help text const HELPTEXT_PREFIX: &str = "\u{001b}[37;49;2m"; // ASCII Reset formatting escape code const RESET: &str = "\u{001b}[0m"; // Helper function to keep things DRY // Takes a dyn Error.source() and returns a Vec of Strings representing all the // .sources() in the error chain (if any) fn error_sources(mut source: Option<&(dyn Error + 'static)>) -> Option<Vec<String>> { /* Check if we have any sources to derive reasons from */ if source.is_some() { /* Add all the error sources to a list of reasons for the error */ let mut reasons = Vec::new(); while let Some(error) = source { reasons.push(error.to_string()); source = error.source(); } Some(reasons) } else { None } } /********* * TRAIT * *********/ // Helper Functions /// Convenience function that converts the summary into pretty String. fn pretty_summary(summary: &str) -> String { [SUMMARY_PREFIX, summary, RESET].concat() } /// Convenience function that converts the reasons into pretty String. fn pretty_reasons(reasons: Reasons) -> Option<String> { /* Print list of Reasons (if any) */ if let Some(reasons) = reasons { /* Vector to store the intermediate bullet point strings */ let mut reason_strings = Vec::with_capacity(reasons.len()); for reason in reasons { let bullet_point = [REASON_PREFIX, &reason].concat(); reason_strings.push(bullet_point); } /* Join the buller points with a newline, append a RESET ASCII escape code to the end */ Some([&reason_strings.join("\n"), RESET].concat()) } else { None } } /// Convenience function that converts the help text into pretty String. fn pretty_helptext(helptext: Helptext) -> Option<String> { if let Some(helptext) = helptext { Some([HELPTEXT_PREFIX, &helptext, RESET].concat()) } else { None } } /// You can implement UFE on your error types pretty print them. The default /// implementation will print Error: <your error .to_string()> followed by a list /// of reasons that are any errors returned by .source(). You should only /// override the summary, reasons and help text functions. The pretty print /// versions of these are used by print(), print_and_exit() and contain the /// formatting. If you wish to change the formatting you should update it with /// the formatting functions. pub trait UFE: Error { /************** * IMPLENT ME * **************/ /// Returns a summary of the error. This will be printed in red, prefixed /// by "Error: ", at the top of the error message. fn summary(&self) -> String { self.to_string() } /// Returns a vector of Strings that will be listed as bullet points below /// the summary. By default, lists any errors returned by .source() /// recursively. fn reasons(&self) -> Option<Vec<String>> { /* Helper function to keep things DRY */ error_sources(self.source()) } /// Returns help text that is listed below the reasons in a muted fashion. /// Useful for additional details, or suggested next steps. fn helptext(&self) -> Option<String> { None } /********** * USE ME * **********/ /// Prints the formatted error. /// # Example /// ``` /// use user_error::{UserFacingError, UFE}; /// UserFacingError::new("File failed to open") /// .reason("File not found") /// .help("Try: touch file.txt") /// .print(); /// ``` fn print(&self) { /* Print Summary */ eprintln!("{}", pretty_summary(&self.summary())); /* Print list of Reasons (if any) */ if let Some(reasons) = pretty_reasons(self.reasons()) { eprintln!("{}", reasons); } /* Print help text (if any) */ if let Some(helptext) = pretty_helptext(self.helptext()) { eprintln!("{}", helptext); } } /// Convenience function that pretty prints the error and exits the program. /// # Example /// ```should_panic /// use user_error::{UserFacingError, UFE}; /// UserFacingError::new("File failed to open") /// .reason("File not found") /// .help("Try: touch file.txt") /// .print_and_exit(); /// ``` fn print_and_exit(&self) { self.print(); std::process::exit(1) } /// Consumes the UFE and returns a UserFacingError. Useful if you want /// access to additional functions to edit the error message before exiting /// the program. /// # Example /// ``` /// use user_error::{UserFacingError, UFE}; /// use std::fmt::{self, Display}; /// use std::error::Error; /// /// #[derive(Debug)] /// struct MyError {} /// /// impl Display for MyError { /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { /// write!(f, "MyError") /// } /// } /// /// impl Error for MyError { /// fn source(&self) -> Option<&(dyn Error + 'static)> { None } /// } /// /// impl UFE for MyError {} /// /// fn main() { /// let me = MyError {}; /// me.print(); /// me.into_ufe() /// .help("Added help text") /// .print(); /// } /// ``` fn into_ufe(&self) -> UserFacingError { UserFacingError { summary: self.summary(), reasons: self.reasons(), helptext: self.helptext(), source: None, } } } /********** * STRUCT * **********/ type Summary = String; type Reasons = Option<Vec<String>>; type Helptext = Option<String>; type Source = Option<Box<(dyn Error)>>; /// The eponymous struct. You can create a new one from using /// user_error::UserFacingError::new() however I recommend you use your own /// error types and have them implement UFE instead of using UserFacingError /// directly. This is more of an example type, or a way to construct a pretty /// messages without implementing your own error type. #[derive(Debug)] pub struct UserFacingError { summary: Summary, reasons: Reasons, helptext: Helptext, source: Source, } /****************** * IMPLEMENTATION * ******************/ // Implement Display so our struct also implements std::error::Error impl Display for UserFacingError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let summary = pretty_summary(&self.summary()); let reasons = pretty_reasons(self.reasons()); let helptext = pretty_helptext(self.helptext()); // Love this - thanks Rust! match (summary, reasons, helptext) { (summary, None, None) => writeln!(f, "{}", summary), (summary, Some(reasons), None) => writeln!(f, "{}\n{}", summary, reasons), (summary, None, Some(helptext)) => writeln!(f, "{}\n{}", summary, helptext), (summary, Some(reasons), Some(helptext)) => { writeln!(f, "{}\n{}\n{}", summary, reasons, helptext) } } } } // Implement std::error::Error impl Error for UserFacingError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self.source { Some(_) => self.source.as_deref(), None => None, } } } // Implement our own trait for our example struct // Cloning is not super efficient but this should be the last thing a program // does, and it will only do it once so... ¯\_(ツ)_/¯ impl UFE for UserFacingError { fn summary(&self) -> Summary { self.summary.clone() } fn reasons(&self) -> Reasons { self.reasons.clone() } fn helptext(&self) -> Helptext { self.helptext.clone() } } // Helper function to keep things DRY fn get_ufe_struct_members(error: &(dyn Error)) -> (Summary, Reasons) { /* Error Display format is the summary */ let summary = error.to_string(); /* Form the reasons from the error source chain */ let reasons = error_sources(error.source()); (summary, reasons) } /// Allows you to create UserFacingErrors From std::io::Error for convenience /// You should really just implement UFE for your error type, but if you wanted /// to convert before quitting so you could add help text of something you can /// use this. impl From<std::io::Error> for UserFacingError { fn from(error: std::io::Error) -> UserFacingError { let (summary, reasons) = get_ufe_struct_members(&error); UserFacingError { summary, reasons, helptext: None, source: Some(Box::new(error)), } } } /// Allows you to create UserFacingErrors From std Errors. /// You should really just implement UFE for your error type, but if you wanted /// to convert before quitting so you could add help text of something you can /// use this. impl From<Box<(dyn Error)>> for UserFacingError { fn from(error: Box<(dyn Error)>) -> UserFacingError { let (summary, reasons) = get_ufe_struct_members(error.as_ref()); UserFacingError { summary, reasons, helptext: None, source: Some(error), } } } /// Allows you to create UserFacingErrors From std Errors. /// You should really just implement UFE for your error type, but if you wanted /// to convert before quitting so you could add help text of something you can /// use this. impl From<&(dyn Error)> for UserFacingError { fn from(error: &(dyn Error)) -> UserFacingError { let (summary, reasons) = get_ufe_struct_members(error); UserFacingError { summary, reasons, helptext: None, source: None, } } } /// Allows you to create UserFacingErrors From std Errors wrapped in a Result /// You should really just implement UFE for your error type, but if you wanted /// to convert before quitting so you could add help text of something you can /// use this. impl<T: Debug> From<Result<T, Box<dyn Error>>> for UserFacingError { fn from(error: Result<T, Box<dyn Error>>) -> UserFacingError { /* Panics if you try to convert an Ok() Result to a UserFacingError */ let error = error.unwrap_err(); let (summary, reasons) = get_ufe_struct_members(error.as_ref()); UserFacingError { summary, reasons, helptext: None, source: Some(error), } } } impl UserFacingError { /// This is how users create a new User Facing Error. The value passed to /// new() will be used as an error summary. Error summaries are displayed /// first, prefixed by 'Error: '. /// # Example /// ``` /// # use user_error::UserFacingError; /// let err = UserFacingError::new("File failed to open"); /// ``` pub fn new<S: Into<String>>(summary: S) -> UserFacingError { UserFacingError { summary: summary.into(), reasons: None, helptext: None, source: None, } } /// Replace the error summary. /// # Example /// ``` /// # use user_error::UserFacingError; /// let mut err = UserFacingError::new("File failed to open"); /// err.update("Failed Task"); /// ``` pub fn update<S: Into<String>>(&mut self, summary: S) { self.summary = summary.into(); } /// Replace the error summary and add the previous error summary to the /// list of reasons /// # Example /// ``` /// # use user_error::UserFacingError; /// let mut err = UserFacingError::new("File failed to open"); /// err.push("Failed Task"); /// ``` pub fn push<S: Into<String>>(&mut self, new_summary: S) { // Add the old summary to the list of reasons let old_summary = self.summary(); match self.reasons.as_mut() { Some(reasons) => reasons.insert(0, old_summary), None => self.reasons = Some(vec![old_summary]), } // Update the summary self.summary = new_summary.into(); } /// Add a reason to the UserFacingError. Reasons are displayed in a /// bulleted list below the summary, in the reverse order they were added. /// # Example /// ``` /// # use user_error::UserFacingError; /// let err = UserFacingError::new("File failed to open") /// .reason("File not found") /// .reason("Directory cannot be entered"); /// ``` pub fn reason<S: Into<String>>(mut self, reason: S) -> UserFacingError { self.reasons = match self.reasons { Some(mut reasons) => { reasons.push(reason.into()); Some(reasons) } None => Some(vec![reason.into()]), }; self } // Return ref to previous? /// Clears all reasons from a UserFacingError. /// # Example /// ``` /// # use user_error::UserFacingError; /// let mut err = UserFacingError::new("File failed to open") /// .reason("File not found") /// .reason("Directory cannot be entered"); /// err.clear_reasons(); /// ``` pub fn clear_reasons(&mut self) { self.reasons = None; } /// Add help text to the error. Help text is displayed last, in a muted /// fashion. /// # Example /// ``` /// # use user_error::UserFacingError; /// let err = UserFacingError::new("File failed to open") /// .reason("File not found") /// .help("Check if the file exists."); /// ``` pub fn help<S: Into<String>>(mut self, helptext: S) -> UserFacingError { self.helptext = Some(helptext.into()); self } /// Clears all the help text from a UserFacingError. /// # Example /// ``` /// # use user_error::UserFacingError; /// let mut err = UserFacingError::new("File failed to open") /// .reason("File not found") /// .reason("Directory cannot be entered") /// .help("Check if the file exists."); /// err.clear_helptext(); /// ``` pub fn clear_helptext(&mut self) { self.helptext = None; } } #[cfg(test)] mod tests { use super::*; // Statics to keep the testing DRY/cleaner static S: &'static str = "Test Error"; static R: &'static str = "Reason 1"; static H: &'static str = "Try Again"; #[test] fn new_test() { eprintln!("{}", UserFacingError::new("Test Error")); } #[test] fn summary_test() { let e = UserFacingError::new(S); let expected = [SUMMARY_PREFIX, S, RESET, "\n"].concat(); assert_eq!(e.to_string(), String::from(expected)); eprintln!("{}", e); } #[test] fn helptext_test() { let e = UserFacingError::new(S).help(H); let expected = format!( "{}{}{}\n{}{}{}\n", SUMMARY_PREFIX, S, RESET, HELPTEXT_PREFIX, H, RESET ); assert_eq!(e.to_string(), expected); eprintln!("{}", e); } #[test] fn reason_test() { let e = UserFacingError::new(S).reason(R).reason(R); /* Create Reasons String */ let reasons = vec![String::from(R), String::from(R)]; let mut reason_strings = Vec::with_capacity(reasons.len()); for reason in reasons { let bullet_point = [REASON_PREFIX, &reason].concat(); reason_strings.push(bullet_point); } // Join the bullet points with a newline, append a RESET ASCII escape // code to the end. let reasons = [&reason_strings.join("\n"), RESET].concat(); let expected = format!("{}{}{}\n{}\n", SUMMARY_PREFIX, S, RESET, reasons); assert_eq!(e.to_string(), expected); eprintln!("{}", e); } #[test] fn push_test() { let mut e = UserFacingError::new(S).reason("R1"); e.push("R2"); /* Create Reasons String */ let reasons = vec![String::from(S), String::from("R1")]; let mut reason_strings = Vec::with_capacity(reasons.len()); for reason in reasons { let bullet_point = [REASON_PREFIX, &reason].concat(); reason_strings.push(bullet_point); } // Join the bullet points with a newline, append a RESET ASCII escape // code to the end let reasons = [&reason_strings.join("\n"), RESET].concat(); let expected = format!("{}{}{}\n{}\n", SUMMARY_PREFIX, "R2", RESET, reasons); assert_eq!(e.to_string(), expected); eprintln!("{}", e); } #[test] fn push_test_empty() { let mut e = UserFacingError::new(S); e.push("S2"); // Create Reasons String let reasons = vec![String::from(S)]; let mut reason_strings = Vec::with_capacity(reasons.len()); for reason in reasons { let bullet_point = [REASON_PREFIX, &reason].concat(); reason_strings.push(bullet_point); } // Join the bullet points with a newline, append a RESET ASCII escape // code to the end let reasons = [&reason_strings.join("\n"), RESET].concat(); let expected = format!("{}{}{}\n{}\n", SUMMARY_PREFIX, "S2", RESET, reasons); assert_eq!(e.to_string(), expected); eprintln!("{}", e); } #[test] fn reason_and_helptext_test() { let e = UserFacingError::new(S).reason(R).reason(R).help(H); // Create Reasons String let reasons = vec![String::from(R), String::from(R)]; let mut reason_strings = Vec::with_capacity(reasons.len()); for reason in reasons { let bullet_point = [REASON_PREFIX, &reason].concat(); reason_strings.push(bullet_point); } // Join the bullet points with a newline, append a RESET ASCII escape // code to the end let reasons = [&reason_strings.join("\n"), RESET].concat(); let expected = format!( "{}{}{}\n{}\n{}{}{}\n", SUMMARY_PREFIX, S, RESET, reasons, HELPTEXT_PREFIX, H, RESET ); assert_eq!(e.to_string(), expected); eprintln!("{}", e); } #[test] fn from_error_test() { let error_text = "Error"; let ioe = std::io::Error::new(std::io::ErrorKind::Other, error_text); // Lose the type fn de(ioe: std::io::Error) -> Box<dyn Error> { Box::new(ioe) } // Convert to UFE let ufe: UserFacingError = de(ioe).into(); let expected = [SUMMARY_PREFIX, error_text, RESET, "\n"].concat(); assert_eq!(ufe.to_string(), expected); } #[test] fn from_error_source_test() { let ufe: UserFacingError = get_super_error().into(); let expected = [ SUMMARY_PREFIX, "SuperError", RESET, "\n", REASON_PREFIX, "Sidekick", RESET, "\n", ] .concat(); assert_eq!(ufe.to_string(), expected); } // Used for to test that source is working correctly #[derive(Debug)] struct SuperError { side: SuperErrorSideKick, } impl Display for SuperError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SuperError") } } impl Error for SuperError { fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.side) } } #[derive(Debug)] struct SuperErrorSideKick; impl Display for SuperErrorSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Sidekick") } } impl Error for SuperErrorSideKick { fn source(&self) -> Option<&(dyn Error + 'static)> { None } } fn get_super_error() -> Result<(), Box<dyn Error>> { Err(Box::new(SuperError { side: SuperErrorSideKick, })) } // Custom Error Type #[derive(Debug)] struct MyError { mssg: String, src: Option<Box<dyn Error>>, } impl Display for MyError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.mssg.to_string()) } } impl Error for MyError { fn source(&self) -> Option<&(dyn Error + 'static)> { self.src.as_deref() } } impl UFE for MyError {} #[test] fn custom_error_implements_ufe() { let me = MyError { mssg: "Program Failed".into(), src: Some(Box::new(MyError { mssg: "Reason 1".into(), src: Some(Box::new(MyError { mssg: "Reason 2".into(), src: None, })), })), }; me.print(); me.into_ufe().help("Helptext Added").print(); } }