From b72fb8e7f6e06f0560aea77eeb70a7f5a29d4755 Mon Sep 17 00:00:00 2001 From: Awiteb Date: Fri, 12 Jul 2024 22:48:54 +0300 Subject: [PATCH] feat: Macro to try the websocket error Signed-off-by: Awiteb --- crates/oxidetalis/src/macros.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/oxidetalis/src/macros.rs b/crates/oxidetalis/src/macros.rs index 26a8732..54c7149 100644 --- a/crates/oxidetalis/src/macros.rs +++ b/crates/oxidetalis/src/macros.rs @@ -17,6 +17,37 @@ //! OxideTalis server macros, to make the code more readable and easier to //! write. +/// Macro to return a [`ServerEvent`] with a [`WsError::InternalServerError`] if +/// the result of an expression is an [`Err`]. +/// +/// ## Example +/// ```rust,ignore +/// fn example() -> ServerEvent { +/// // some_function() returns a Result, if it's an Err, return an +/// // ServerEvent::InternalServerError +/// let result = try_ws!(some_function()); +/// ServerEvent::from(result) +/// } +/// ``` +/// +/// [`ServerEvent`]: crate::websocket::ServerEvent +/// [`WsError::InternalServerError`]: crate::websocket::errors::WsError::InternalServerError +/// [`Err`]: std::result::Result::Err +#[macro_export] +macro_rules! try_ws { + ($result_expr:expr) => { + match $result_expr { + Ok(val) => val, + Err(err) => { + log::error!("Error in try_ws macro: {err:?}"); + return $crate::websocket::ServerEvent::<$crate::websocket::Unsigned>::from( + $crate::websocket::errors::WsError::InternalServerError, + ); + } + } + }; +} + /// Macro to create the `WsError` enum with the given error names and reasons. /// /// ## Example