From 1e736c46ea6bca039216ead96bad2439769f2e23 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 29 Jul 2024 14:14:26 +0300 Subject: [PATCH] feat(src/db.rs): handle time formatting errors without panic Signed-off-by: Lars Wirzenius --- src/db.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/db.rs b/src/db.rs index 2969e3ce..07bd6cd1 100644 --- a/src/db.rs +++ b/src/db.rs @@ -251,7 +251,7 @@ impl Db { let json = serde_json::to_string(&event).map_err(DbError::event_to_json)?; let id = QueueId::default(); - let ts = now(); + let ts = now().map_err(DbError::time_format)?; let mut insert = self.prepare("INSERT INTO event_queue (id, timestamp, event) VALUES (:id, :ts, :e)")?; @@ -391,7 +391,7 @@ impl Db { pub fn push_run(&self, run: Run) -> Result { let id = run.adapter_run_id().ok_or(DbError::without_id())?.clone(); - let json = serde_json::to_string(&run).expect("serialize BrokerEvent to JSON"); + let json = serde_json::to_string(&run).map_err(DbError::event_to_json)?; let mut insert = self.prepare("INSERT INTO ci_runs (run_id, json) VALUES (:id, :json)")?; insert @@ -429,10 +429,10 @@ impl Db { } } -fn now() -> String { +fn now() -> Result { let fmt = format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:6]Z"); - OffsetDateTime::now_utc().format(fmt).expect("format time") + OffsetDateTime::now_utc().format(fmt) } // A wrapper around a statement that remembers its text form. @@ -516,6 +516,10 @@ impl QueuedEvent { /// All errors from this module. #[derive(Debug, thiserror::Error)] pub enum DbError { + /// Error formatting a time as a string. + #[error(transparent)] + Timeformat(#[from] time::error::Format), + #[error("failed to set a busy timer one SQLite database {0}")] BusyTimer(PathBuf, #[source] sqlite::Error), @@ -591,6 +595,10 @@ pub enum DbError { } impl DbError { + fn time_format(e: time::error::Format) -> Self { + Self::Timeformat(e) + } + fn busy_timer(filename: &Path, e: sqlite::Error) -> Self { Self::BusyTimer(filename.into(), e) }