From ce2d77a32c3d8ec09c739be746bf4d63378d9358 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Fri, 30 Dec 2022 10:05:57 -0600 Subject: [PATCH] Implement Display and Error for all errors These standard traits should be implemented for all error types so they can match `dyn Error`, etc. --- src/marionette/error.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/session.rs | 22 ++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/marionette/error.rs b/src/marionette/error.rs index 065bea0..5ef1b4d 100644 --- a/src/marionette/error.rs +++ b/src/marionette/error.rs @@ -26,6 +26,26 @@ impl From for MessageError { } } +impl std::fmt::Display for MessageError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Io(e) => write!(f, "I/O error: {}", e), + Self::Parse(e) => write!(f, "Error parsing message: {}", e), + Self::Utf8(e) => write!(f, "Error parsing message: {}", e), + } + } +} + +impl std::error::Error for MessageError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(e) => Some(e), + Self::Parse(e) => Some(e), + Self::Utf8(e) => Some(e), + } + } +} + #[derive(Debug)] pub enum ConnectionError { Message(MessageError), @@ -50,3 +70,23 @@ impl From for ConnectionError { Self::Json(e) } } + +impl std::fmt::Display for ConnectionError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Io(e) => write!(f, "I/O error: {}", e), + Self::Message(e) => write!(f, "Invalid message: {}", e), + Self::Json(e) => write!(f, "Could not parse JSON value: {}", e), + } + } +} + +impl std::error::Error for ConnectionError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(e) => Some(e), + Self::Message(e) => Some(e), + Self::Json(e) => Some(e), + } + } +} diff --git a/src/session.rs b/src/session.rs index 49d9264..a081a66 100644 --- a/src/session.rs +++ b/src/session.rs @@ -30,6 +30,28 @@ impl From for SessionError { } } +impl std::fmt::Display for SessionError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + Self::Browser(e) => write!(f, "Error launching browser: {}", e), + Self::Io(e) => write!(f, "I/O error: {}", e), + Self::Connection(e) => write!(f, "Connection error: {}", e), + Self::InvalidState(e) => write!(f, "Invalid state: {}", e), + } + } +} + +impl std::error::Error for SessionError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Browser(e) => Some(e), + Self::Io(e) => Some(e), + Self::Connection(e) => Some(e), + Self::InvalidState(_) => None, + } + } +} + pub struct Session { browser: Browser, marionette: Marionette,