From 376d9c1896d6e23970071a6e9da01f9f0842c0d0 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sun, 24 Feb 2019 10:48:36 +0100 Subject: Let errors propagate out of main too. Makes error messages from the program slightly nicer, but still a bit cryptic for the casual user. --- src/error.rs | 20 ++++++++++++++++++++ src/main.rs | 17 +++++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/error.rs b/src/error.rs index ed17362..b0ab95d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -27,6 +27,26 @@ pub enum Error { JsonError(serde_json::error::Error), } +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Error::InvalidHeaderValue(e) => e.fmt(f), + Error::ReqwestError(e) => e.fmt(f), + Error::JsonError(e) => e.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn cause(&self) -> Option<&std::error::Error> { + match self { + Error::InvalidHeaderValue(e) => Some(e), + Error::ReqwestError(e) => Some(e), + Error::JsonError(e) => Some(e), + } + } +} + impl From for Error { fn from(err: reqwest::header::InvalidHeaderValue) -> Error { Error::InvalidHeaderValue(err) diff --git a/src/main.rs b/src/main.rs index 014e8b2..5e18bac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,14 +18,17 @@ use dotenv; use oslobike; +use std::error::Error; +use std::result::Result; -fn main() { - let api_key = dotenv::var("OSLOBIKE_APIKEY").expect("No API key defined!"); - let api = oslobike::Api::new(api_key).unwrap(); - let stations = api.stations().unwrap(); - let station_availability = api.station_availability().unwrap(); +fn main() -> Result<(), Box> { + let api_key = dotenv::var("OSLOBIKE_APIKEY") + .map_err(|_| "No API key defined.")?; - for station in api.stations().unwrap() { + let api = oslobike::Api::new(api_key)?; + let station_availability = api.station_availability()?; + + for station in api.stations()? { let a = station_availability.iter().find(|s| s.id == station.id).unwrap(); println!("{:>4} {:<32}: {:>2} bikes, {:>2} locks of {:>2} total", station.id, @@ -34,4 +37,6 @@ fn main() { a.availability.locks, station.number_of_locks); } + + Ok(()) } -- cgit v1.2.3