aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorHarald Eilertsen <haraldei@anduin.net>2019-02-24 10:48:36 +0100
committerHarald Eilertsen <haraldei@anduin.net>2019-02-24 10:48:36 +0100
commit376d9c1896d6e23970071a6e9da01f9f0842c0d0 (patch)
treee93ede8da01fe7d931d19b0b30b0dfbc4d66c1ca
parentd64eb2a487f3e195bfdded2bf98d55405301d3ef (diff)
downloadoslobike-376d9c1896d6e23970071a6e9da01f9f0842c0d0.tar.gz
oslobike-376d9c1896d6e23970071a6e9da01f9f0842c0d0.tar.bz2
oslobike-376d9c1896d6e23970071a6e9da01f9f0842c0d0.zip
Let errors propagate out of main too.
Makes error messages from the program slightly nicer, but still a bit cryptic for the casual user.
-rw-r--r--src/error.rs20
-rw-r--r--src/main.rs17
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<reqwest::header::InvalidHeaderValue> 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<dyn Error>> {
+ 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(())
}