Wrapping errors

An alternative to boxing errors is to wrap them in your own error type.

  1. use std::error;
  2. use std::num::ParseIntError;
  3. use std::fmt;
  4. type Result<T> = std::result::Result<T, DoubleError>;
  5. #[derive(Debug)]
  6. enum DoubleError {
  7. EmptyVec,
  8. // We will defer to the parse error implementation for their error.
  9. // Supplying extra info requires adding more data to the type.
  10. Parse(ParseIntError),
  11. }
  12. impl fmt::Display for DoubleError {
  13. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  14. match *self {
  15. DoubleError::EmptyVec =>
  16. write!(f, "please use a vector with at least one element"),
  17. // This is a wrapper, so defer to the underlying types' implementation of `fmt`.
  18. DoubleError::Parse(ref e) => e.fmt(f),
  19. }
  20. }
  21. }
  22. impl error::Error for DoubleError {
  23. fn description(&self) -> &str {
  24. match *self {
  25. DoubleError::EmptyVec => "empty vectors not allowed",
  26. // This already impls `Error`, so defer to its own implementation.
  27. DoubleError::Parse(ref e) => e.description(),
  28. }
  29. }
  30. fn cause(&self) -> Option<&error::Error> {
  31. match *self {
  32. DoubleError::EmptyVec => None,
  33. // The cause is the underlying implementation error type. Is implicitly
  34. // cast to the trait object `&error::Error`. This works because the
  35. // underlying type already implements the `Error` trait.
  36. DoubleError::Parse(ref e) => Some(e),
  37. }
  38. }
  39. }
  40. // Implement the conversion from `ParseIntError` to `DoubleError`.
  41. // This will be automatically called by `?` if a `ParseIntError`
  42. // needs to be converted into a `DoubleError`.
  43. impl From<ParseIntError> for DoubleError {
  44. fn from(err: ParseIntError) -> DoubleError {
  45. DoubleError::Parse(err)
  46. }
  47. }
  48. fn double_first(vec: Vec<&str>) -> Result<i32> {
  49. let first = vec.first().ok_or(DoubleError::EmptyVec)?;
  50. let parsed = first.parse::<i32>()?;
  51. Ok(2 * parsed)
  52. }
  53. fn print(result: Result<i32>) {
  54. match result {
  55. Ok(n) => println!("The first doubled is {}", n),
  56. Err(e) => println!("Error: {}", e),
  57. }
  58. }
  59. fn main() {
  60. let numbers = vec!["42", "93", "18"];
  61. let empty = vec![];
  62. let strings = vec!["tofu", "93", "18"];
  63. print(double_first(numbers));
  64. print(double_first(empty));
  65. print(double_first(strings));
  66. }

This adds a bit more boilerplate for handling errors and might not be needed in
all applications. There are some libraries that can take care of the boilerplate
for you.

See also:

From::from and Enums