Skip to main content

radroots_sql_core/
error.rs

1#![cfg_attr(any(feature = "embedded", target_os = "espidf"), no_std)]
2
3#[cfg(any(feature = "embedded", target_os = "espidf"))]
4extern crate alloc;
5
6use serde::Serialize;
7use thiserror::Error;
8
9#[cfg(any(feature = "embedded", target_os = "espidf"))]
10use alloc::string::String;
11
12#[derive(Error, Debug, Clone, Serialize)]
13pub enum SqlError {
14    #[error("invalid argument: {0}")]
15    InvalidArgument(String),
16    #[error("{0} not found")]
17    NotFound(String),
18    #[error("serialization error: {0}")]
19    SerializationError(String),
20    #[error("invalid query: {0}")]
21    InvalidQuery(String),
22    #[error("internal error")]
23    Internal,
24    #[error("unsupported on this platform")]
25    UnsupportedPlatform,
26}
27
28impl SqlError {
29    pub fn code(&self) -> &'static str {
30        match self {
31            SqlError::InvalidArgument(_) => "ERR_INVALID_ARGUMENT",
32            SqlError::NotFound(_) => "ERR_NOT_FOUND",
33            SqlError::SerializationError(_) => "ERR_SERIALIZATION",
34            SqlError::InvalidQuery(_) => "ERR_INVALID_QUERY",
35            SqlError::Internal => "ERR_INTERNAL",
36            SqlError::UnsupportedPlatform => "ERR_UNSUPPORTED_PLATFORM",
37        }
38    }
39
40    pub fn to_json(&self) -> serde_json::Value {
41        serde_json::json!({ "code": self.code(), "message": self.to_string() })
42    }
43}
44
45impl From<serde_json::Error> for SqlError {
46    fn from(e: serde_json::Error) -> Self {
47        SqlError::SerializationError(e.to_string())
48    }
49}
50
51#[cfg(feature = "native")]
52impl From<rusqlite::Error> for SqlError {
53    fn from(e: rusqlite::Error) -> Self {
54        SqlError::InvalidQuery(e.to_string())
55    }
56}