26  Throwing errors

Objective

Perform early function validation and throw an error from Rust.

So far we have not been performing any validation of our inputs.

If we pass an incorrect value to geohash::encode() we will receive an error. There are 3 ways that we can receive an error:

In a moment we will vectorize on x and y but not on length. So, let’s perform some validation.

We can use throw_r_error("error message") to emit an error directly from Rust.

Exercise

  • Add a validation step in gh_encode() the ensures length is within the range [1, 12]
  • If length is an invalid value, emit an error using throw_r_error()
View solution

Modify your src/lib.rs file to have:

#[extendr]
fn gh_encode(x: f64, y: f64, length: usize) -> String {
    if length == 0 || length > 12 {
        throw_r_error("`length` must be between 1 and 12");
    }

    let coord = Coord { x, y };
    encode(coord, length).unwrap()
}

Run rextendr::document() and devtools::load_all() to register the changes to your function.

Run gh_encode(3.0, 0.14, 100L) with your new function.