use tracing::error; #[derive(Debug, thiserror::Error)] pub enum ServerError { #[error(transparent)] Wire(#[from] common::error::Error), #[error("{0}")] Internal(String), } impl From for common::error::Error { fn from(value: ServerError) -> Self { match value { ServerError::Wire(error) => error, ServerError::Internal(message) => { error!("{message}"); common::error::Error::Server } } } } impl From for ServerError { fn from(error: turso::Error) -> Self { match &error { turso::Error::Constraint(message) if message.starts_with("UNIQUE constraint failed") => { common::error::Error::Taken.into() } turso::Error::Constraint(message) if message.starts_with("FOREIGN KEY constraint failed") => { common::error::Error::NotFound.into() } _ => ServerError::Internal(error.to_string()), } } } pub fn ensure(condition: bool) -> Result<(), ServerError> { ensure_with(condition, common::error::Error::Forbidden) } pub fn ensure_with(condition: bool, error: common::error::Error) -> Result<(), ServerError> { if !condition { return Err(error.into()); } Ok(()) } macro_rules! internal_from { ($($source:ty),+ $(,)?) => { $( impl From<$source> for ServerError { fn from(value: $source) -> Self { ServerError::Internal(value.to_string()) } } )+ }; } internal_from! { std::net::AddrParseError, std::io::Error, tokio::task::JoinError, quinn::ConnectionError, quinn::ReadError, quinn::ReadExactError, quinn::WriteError, quinn::ClosedStream, bitcode::Error, common::config::ConfigError, common::frame::FrameError, common::update::UpdateError, tokio::time::error::Elapsed, }