Basic function parameter validation

Hello

I have a simple function taking a three parameters. I want to input-validate these parameters.
This is my current approach:

    /*
        Method to send a text-message
        :param to: Telephone number to send message to. Format: +xx.xxxxxxxxx
        :param from: Source of message. Format: +xx.xxxxxxxxx
        :param message: Content of message to send
        :return Result<(), &str>: Returns Ok() if successfull. Returns an error otherwise.
    */
    pub async fn send(&self, to: String, from: String, message: String) -> Result<(), &str> {
        // Input validation
        let phone_number_regex = Regex::new(r"\+\d{2,3}\.\d{7,12}").unwrap();
        if message.len() == 0 {
            return Err("Message cannot be empty.");
        }
        if message.len() > 160 {
            return Err("Message cannot be more than 160 characters");
        }
        if !phone_number_regex.is_match(&to) || !phone_number_regex.is_match(&from) {
            return Err(
                "Phone numbers must be in the format: +xx.yyyyyyyyy where xx is the country code.",
            );
        }

        //...

        Ok(())
    }

This is how I call it in my main.rs:

let to = "".to_string();
let from = "".to_string();
let message = "test".to_string();

send(to, from, message).await.ok();

I basically want to check if the parameters pass some basic tests as not being empty, not being too long,... If a test fails I want to display an error and terminate the function. But I do NOT want to exit the whole program.

Also, currently when an error occurs the error-message is not outputted. How do I output the &str the function returns if invalid parameters are given?

match tigron_sms.send(to, from, message).await {
        Ok(_) => (),
        Err(e) => println!("{}", e),
    };

works. But I am searching for a shorter solution if that exists.

Anyway, how would I improve this code?

Your function looks fine.
As for the error-message printing, simply use an if let since you are throwing one branch away:

if let Err(e) = tigron_sms.send(to, from, mesesage).await {
    println!("{}", e);
}
1 Like

There's also eprintln! if standard error would be more appropriate.

When would eprintln!() be better practice than using Result<> and Err()?

@quinedot meant to say use eprintln! instead of println!. The only difference between the two is that the former prints to stderr while the later prints to stdout. Considering the fact that you are printing an error, using eprintln! makes sense, unless you need the errors to come out on stdout.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.