From 1bf620feca12126ad3700a82202ac92281056f9f Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Mon, 29 Jul 2024 13:53:40 +0300 Subject: [PATCH] feat(src/db.rs): handle JSON encoding errors without panic Signed-off-by: Lars Wirzenius --- src/db.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/db.rs b/src/db.rs index 8620915e..2969e3ce 100644 --- a/src/db.rs +++ b/src/db.rs @@ -248,7 +248,7 @@ impl Db { /// Add a new event to the event queue, returning its id. pub fn push_queued_event(&self, event: BrokerEvent) -> Result { - let json = serde_json::to_string(&event).expect("serialize BrokerEvent to JSON"); + let json = serde_json::to_string(&event).map_err(DbError::event_to_json)?; let id = QueueId::default(); let ts = now(); @@ -558,6 +558,10 @@ pub enum DbError { #[error("failed to parse queued event as JSON: {0}")] EventFromJson(String, #[source] serde_json::Error), + /// Can't convert broker event into JSON. + #[error("failed to convert broker event into JSON")] + EventToJson(#[source] serde_json::Error), + #[error("failed to insert an event into queue")] PushEvent(String, #[source] sqlite::Error), @@ -639,6 +643,10 @@ impl DbError { Self::EventFromJson(json.into(), e) } + fn event_to_json(e: serde_json::Error) -> Self { + Self::EventToJson(e) + } + fn push_event(sql: &str, e: sqlite::Error) -> Self { Self::PushEvent(sql.into(), e) }