How it works...

The std library automatically converts any type that implements the Error trait into the trait object Box<Error> via the From trait object. However, a user may use many external libraries, and different libraries provide their own error types. In order to define a valid Result<T, E> type, perform the following tasks:

  • Define a new wrapper error type around the library's standard error types
  • Convert the error types into String or any other type that is convenient to handle
  • Box the error types into the Box<Error> type

In this recipe, we started off by calling the standard libraries std::error, std::fmt, and std::num::ParseIntError. We then created an alias Result<T> for std::result::Result<T, Box<error::Error>>. Next, we created our own customized enum error type named CustomError, which had two types of data: EmptyVec and Parse(ParseIntError).

The compiler is capable of providing basic implementations for some traits via the #[derive] attribute, where an attribute is a metadata applied to some module, crate, or item. We use the #[derive(Debug)] for getting an output format that is programmer-facing and has more debugging context.

We converted the standard library's ParseIntError error into the custom error type CustomError by implementing the From trait. We did this because the from method takes in the standard error type ParseIntError as err and returns the CustomError type by setting CustomError::Parse(err).

Now let's see how we implemented custom display functions for the different errors. We used the impl keyword to create a customized fmt::Display for our CustomError error type, where fmt represented the standard library. The fmt method takes in &self, f: &mut fmt::Formatter and returns the standard fmt::Result. We used the match statement to identify what type of error it was and display the corresponding error messages. In the case of CustomError::EmptyVec, we printed this error message: please use a vector with at least one element. In the case of CustomError::Parse, we formatted and printed the extra information of the type.

To implement Box<Error>, we had to implement the Error trait where we had two methods: description and cause. These methods take the value of the trait and return them. In the description method, using the match statement, we assigned a description about the error types; here we matched CustomError::EmptyVec to empty vectors not allowed and CustomError::Parse(ref e) to e.description(). Similarly, in the case of cause, we had sample values that led to the error, and we matched CustomError::EmptyVec to None and CustomError::Parse(ref e) to Some(e).

Let's check out the working of all the functional units:

  • double_first: This function takes in the vec input and returns Result<i32>. In our case, it took the first value of the vector sent to it using the vec.first method with the try! macro and assigned it to the first variable. If no values are provided, then it would enter ok_or, where it changes the error type to CustomError::EmptyVec. Next, we checked whether we were able to parse the string value to a valid integer value by first.parse::<i32>(), using the try! macro and assigning it to the parsed variable. If this is successful, we double it by multiplying the parsed integer by 2. In the Ok data type, it returns the enum type Result<i32>; else, it takes the error value parsed by the error type.
  • print: This function takes in Result<i32>. Using the match statement, we check whether we have an Ok or Err case to print the corresponding statement.

In the main function, we had vectors. Among these, one was a number, where we had the correct input type for producing the output without any errors. The next one was empty, meaning there were no values in the vector. The other one was strings, where we had the first value of a string of character values that couldn't be parsed into an integer. When we call the double_first function with these input values, we get the corresponding errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10