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