From 5d0806a8c9803c667ea01588dd6ee59ab02a9372 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 26 Oct 2021 08:48:50 -0700 Subject: [PATCH] fix(serde): gracefully handle window ser errors I came across some panics when trying to run the custom serialization of the Window struct for windows that were in the process of being destroyed recently. This commit replaces all of the expect() calls in the Serialize implementation for Window with calls to serde::ser::Error::custom() which should fail gracefully without rendering the thread that previously panicked as useless. fix #55 --- komorebi/src/window.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/komorebi/src/window.rs b/komorebi/src/window.rs index 976cedcb..1a18117f 100644 --- a/komorebi/src/window.rs +++ b/komorebi/src/window.rs @@ -4,6 +4,7 @@ use std::fmt::Formatter; use color_eyre::eyre::anyhow; use color_eyre::Result; +use serde::ser::Error; use serde::ser::SerializeStruct; use serde::Serialize; use serde::Serializer; @@ -56,12 +57,28 @@ impl Serialize for Window { { let mut state = serializer.serialize_struct("Window", 5)?; state.serialize_field("hwnd", &self.hwnd)?; - state.serialize_field("title", &self.title().expect("could not get window title"))?; - state.serialize_field("exe", &self.exe().expect("could not get window exe"))?; - state.serialize_field("class", &self.class().expect("could not get window class"))?; + state.serialize_field( + "title", + &self + .title() + .map_err(|_| S::Error::custom("could not get window title"))?, + )?; + state.serialize_field( + "exe", + &self + .exe() + .map_err(|_| S::Error::custom("could not get window exe"))?, + )?; + state.serialize_field( + "class", + &self + .class() + .map_err(|_| S::Error::custom("could not get window class"))?, + )?; state.serialize_field( "rect", - &WindowsApi::window_rect(self.hwnd()).expect("could not get window rect"), + &WindowsApi::window_rect(self.hwnd()) + .map_err(|_| S::Error::custom("could not get window rect"))?, )?; state.end() }