diff options
author | Jesse Luehrs <doy@tozt.net> | 2019-08-18 23:45:33 -0400 |
---|---|---|
committer | Jesse Luehrs <doy@tozt.net> | 2019-08-18 23:45:33 -0400 |
commit | 3539ceb20f5383a332a8ad1fcab816cf083f277e (patch) | |
tree | 5cea964a052c7c0bd967ede1d4283b75eba58ea5 /src/ynab/client.rs | |
parent | ca8b49db6c369bc9b5c71a43ca7eb31140223cf1 (diff) | |
download | ynab-reimbursements-3539ceb20f5383a332a8ad1fcab816cf083f277e.tar.gz ynab-reimbursements-3539ceb20f5383a332a8ad1fcab816cf083f277e.zip |
better error handling
Diffstat (limited to 'src/ynab/client.rs')
-rw-r--r-- | src/ynab/client.rs | 65 |
1 files changed, 48 insertions, 17 deletions
diff --git a/src/ynab/client.rs b/src/ynab/client.rs index 4b935c3..19b456b 100644 --- a/src/ynab/client.rs +++ b/src/ynab/client.rs @@ -1,3 +1,19 @@ +#[derive(Debug, snafu::Snafu)] +pub enum Error { + // ynab-api error types don't implement Error, so can't use the + // auto-source behavior + #[snafu(display("failed to update transactions: {}", source_msg))] + UpdateTransactions { source_msg: String }, + + #[snafu(display("failed to get budgets: {}", source_msg))] + GetBudgets { source_msg: String }, + + #[snafu(display("failed to get budget {}: {}", id, source_msg))] + GetBudgetById { id: String, source_msg: String }, +} + +pub type Result<T> = std::result::Result<T, Error>; + pub struct Client { api: ynab_api::apis::client::APIClient, } @@ -15,31 +31,46 @@ impl Client { } } - pub fn default_budget(&self) -> ynab_api::models::BudgetDetail { - let budgets = - self.api.budgets_api().get_budgets().unwrap().data.budgets; - let budget = budgets.iter().next().unwrap(); - self.api + pub fn default_budget(&self) -> Result<ynab_api::models::BudgetDetail> { + let budget_id = self + .api .budgets_api() - .get_budget_by_id(&budget.id, 0) - .unwrap() + .get_budgets() + .map_err(|e| Error::GetBudgets { + source_msg: format!("{:?}", e), + })? .data - .budget + .budgets + .iter() + .next() + .ok_or_else(|| Error::GetBudgets { + source_msg: "no budgets found".to_string(), + })? + .id + .clone(); + Ok(self + .api + .budgets_api() + .get_budget_by_id(&budget_id, 0) + .map_err(|e| Error::GetBudgetById { + id: budget_id.clone(), + source_msg: format!("{:?}", e), + })? + .data + .budget) } pub fn update_transactions( &self, budget_id: &str, transactions: ynab_api::models::UpdateTransactionsWrapper, - ) -> Option<String> { - let res = self - .api + ) -> Result<()> { + self.api .transactions_api() - .update_transactions(budget_id, transactions); - if let Err(e) = res { - Some(format!("{:?}", e)) - } else { - None - } + .update_transactions(budget_id, transactions) + .map(|_| ()) + .map_err(|e| Error::UpdateTransactions { + source_msg: format!("{:?}", e), + }) } } |