Defining an error type

Sometimes it simplifies the code to mask all of the different errors with a
single type of error. We’ll show this with a custom error.

Rust allows us to define our own error types. In general, a “good” error type:

  • Represents different errors with the same type
  • Presents nice error messages to the user
  • Is easy to compare with other types
    • Good: Err(EmptyVec)
    • Bad: Err("Please use a vector with at least one element".to_owned())
  • Can hold information about the error
    • Good: Err(BadChar(c, position))
    • Bad: Err("+ cannot be used here".to_owned())
  • Composes well with other errors
  1. use std::error;
  2. use std::fmt;
  3. use std::num::ParseIntError;
  4. type Result<T> = std::result::Result<T, DoubleError>;
  5. #[derive(Debug, Clone)]
  6. // Define our error types. These may be customized for our error handling cases.
  7. // Now we will be able to write our own errors, defer to an underlying error
  8. // implementation, or do something in between.
  9. struct DoubleError;
  10. // Generation of an error is completely separate from how it is displayed.
  11. // There's no need to be concerned about cluttering complex logic with the display style.
  12. //
  13. // Note that we don't store any extra info about the errors. This means we can't state
  14. // which string failed to parse without modifying our types to carry that information.
  15. impl fmt::Display for DoubleError {
  16. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  17. write!(f, "invalid first item to double")
  18. }
  19. }
  20. // This is important for other errors to wrap this one.
  21. impl error::Error for DoubleError {
  22. fn description(&self) -> &str {
  23. "invalid first item to double"
  24. }
  25. fn cause(&self) -> Option<&error::Error> {
  26. // Generic error, underlying cause isn't tracked.
  27. None
  28. }
  29. }
  30. fn double_first(vec: Vec<&str>) -> Result<i32> {
  31. vec.first()
  32. // Change the error to our new type.
  33. .ok_or(DoubleError)
  34. .and_then(|s| s.parse::<i32>()
  35. // Update to the new error type here also.
  36. .map_err(|_| DoubleError)
  37. .map(|i| 2 * i))
  38. }
  39. fn print(result: Result<i32>) {
  40. match result {
  41. Ok(n) => println!("The first doubled is {}", n),
  42. Err(e) => println!("Error: {}", e),
  43. }
  44. }
  45. fn main() {
  46. let numbers = vec!["42", "93", "18"];
  47. let empty = vec![];
  48. let strings = vec!["tofu", "93", "18"];
  49. print(double_first(numbers));
  50. print(double_first(empty));
  51. print(double_first(strings));
  52. }