//! The one error type of the host. //! //! An error is a message for the user. It crosses IPC as a plain JSON string, //! so the frontend and the plugins receive the same text as before this type existed. //! Every conversion keeps the `Display` text of its source error without changes. use std::fmt; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error(String); pub type Result = std::result::Result; impl Error { pub fn new(message: impl Into) -> Self { Self(message.into()) } /// Use the text of a value that has no `From` conversion, such as an error of an indirect dependency. pub fn from_display(error: impl fmt::Display) -> Self { Self(error.to_string()) } } impl fmt::Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(&self.0) } } impl serde::Serialize for Error { fn serialize(&self, serializer: S) -> std::result::Result { serializer.serialize_str(&self.0) } } impl From for Error { fn from(message: String) -> Self { Self(message) } } impl From<&str> for Error { fn from(message: &str) -> Self { Self(message.to_owned()) } } impl From for String { fn from(error: Error) -> Self { error.0 } } impl From> for Error { fn from(error: std::sync::PoisonError) -> Self { Self(error.to_string()) } } macro_rules! from_display { ($($source:ty),* $(,)?) => { $(impl From<$source> for Error { fn from(error: $source) -> Self { Self(error.to_string()) } })* }; } from_display!( std::io::Error, std::path::StripPrefixError, std::str::Utf8Error, std::string::FromUtf8Error, std::sync::mpsc::RecvError, std::time::SystemTimeError, serde_json::Error, notify::Error, tauri::Error, tauri_plugin_opener::Error, uuid::Error, zip::result::ZipError, ); #[cfg(windows)] from_display!(windows::core::Error); #[cfg(test)] mod tests { use super::*; #[test] fn serializes_as_the_plain_message() { let error = Error::new("Save blocked: file changed on disk."); assert_eq!(serde_json::to_string(&error).unwrap(), r#""Save blocked: file changed on disk.""#); assert_eq!( serde_json::to_value(Err::<(), _>(error.clone())).unwrap(), serde_json::to_value(Err::<(), _>("Save blocked: file changed on disk.")).unwrap(), ); assert_eq!(error.to_string(), "Save blocked: file changed on disk."); } #[test] fn conversions_keep_the_source_text() { let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file"); assert_eq!(Error::from(io).to_string(), "missing file"); let json = serde_json::from_str::("{").unwrap_err(); assert_eq!(Error::from(json.to_string()), Error::from(json)); assert_eq!(Error::from("text"), Error::new(String::from("text"))); assert_eq!(String::from(Error::from_display(42)), "42"); } }