From f9a51b50024f507d8bd42eee8f5d51801c81b78e Mon Sep 17 00:00:00 2001 From: Hanh Date: Tue, 7 Sep 2021 08:53:54 +0800 Subject: [PATCH] Error handling for fetch_prices --- src/prices.rs | 9 +++++---- src/scan.rs | 3 +-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/prices.rs b/src/prices.rs index 04fd876..67bb23a 100644 --- a/src/prices.rs +++ b/src/prices.rs @@ -15,6 +15,7 @@ pub async fn fetch_historical_prices( currency: &str, db: &DbAdapter, ) -> anyhow::Result> { + let json_error = || anyhow::anyhow!("Invalid JSON"); let today = now / DAY_SEC; let from_day = today - days as i64; let latest_quote = db.get_latest_quote(currency)?; @@ -42,12 +43,12 @@ pub async fn fetch_historical_prices( let req = client.get(url).query(¶ms); let res = req.send().await?; let r: serde_json::Value = res.json().await?; - let prices = r["prices"].as_array().unwrap(); + let prices = r["prices"].as_array().ok_or_else(json_error)?; let mut prev_timestamp = 0i64; for p in prices.iter() { - let p = p.as_array().unwrap(); - let ts = p[0].as_i64().unwrap() / 1000; - let price = p[1].as_f64().unwrap(); + let p = p.as_array().ok_or_else(json_error)?; + let ts = p[0].as_i64().ok_or_else(json_error)? / 1000; + let price = p[1].as_f64().ok_or_else(json_error)?; // rounded to daily let date = NaiveDateTime::from_timestamp(ts, 0).date().and_hms(0, 0, 0); let timestamp = date.timestamp(); diff --git a/src/scan.rs b/src/scan.rs index ad4d944..3553e2b 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -298,8 +298,7 @@ pub async fn sync_async( let start = Instant::now(); if get_tx && !my_tx_ids.is_empty() { retrieve_tx_info(&mut client, &db_path2, &new_ids_tx) - .await - .unwrap(); + .await?; } log::info!("Transaction Details : {}", start.elapsed().as_millis());