From 1fbd084baf2a480c90decbb6279761e7697e2250 Mon Sep 17 00:00:00 2001 From: keepsimple1 Date: Tue, 21 Feb 2023 22:23:08 -0800 Subject: [PATCH] handle input errors gracefully in examples (#89) --- examples/query.rs | 11 ++++++++--- examples/register.rs | 22 ++++++++++++++++------ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/examples/query.rs b/examples/query.rs index aab6f5f..9ad0e1a 100644 --- a/examples/query.rs +++ b/examples/query.rs @@ -19,9 +19,14 @@ fn main() { // Create a daemon let mdns = ServiceDaemon::new().expect("Failed to create daemon"); - let mut service_type = std::env::args() - .nth(1) - .expect("it requires a service_type as argument"); + let mut service_type = match std::env::args().nth(1) { + Some(arg) => arg, + None => { + println!("ERROR: require a service_type as argument. For example: "); + println!("cargo run --example query _my-service._udp"); + return; + } + }; // Browse for a service type. service_type.push_str(".local."); diff --git a/examples/register.rs b/examples/register.rs index a176c16..3dade86 100644 --- a/examples/register.rs +++ b/examples/register.rs @@ -14,12 +14,22 @@ use mdns_sd::{ServiceDaemon, ServiceInfo}; fn main() { // Create a new mDNS daemon. let mdns = ServiceDaemon::new().expect("Could not create service daemon"); - let service_type = std::env::args() - .nth(1) - .expect("require a service_type as the 1st argument"); - let instance_name = std::env::args() - .nth(2) - .expect("require a instance_name as the 2nd argument"); + let service_type = match std::env::args().nth(1) { + Some(arg) => arg, + None => { + println!("ERROR: register requires a service_type as the 1st argument. For example:"); + println!("cargo run --example register _my-hello._udp.local. test1"); + return; + } + }; + let instance_name = match std::env::args().nth(2) { + Some(arg) => arg, + None => { + println!("ERROR: require a instance_name as the 2nd argument. For example: "); + println!("cargo run --example register _my-hello._udp.local. test1"); + return; + } + }; // With `enable_addr_auto()`, we can give empty addrs and let the lib find them. // If the caller knows specific addrs to use, then assign the addrs here.