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:
x
is outside of the range [-180, 180]y
is outside of the range [-90, 90]length
is outside of the range [1, 12]
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 ensureslength
is within the range [1, 12] - If
length
is an invalid value, emit an error usingthrow_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 {
"`length` must be between 1 and 12");
throw_r_error(}
let coord = Coord { x, y };
, length).unwrap()
encode(coord}
Run rextendr::document()
and devtools::load_all()
to register the changes to your function.
gh_encode(3.0, 0.14, 100L)
with your new function.