1use color_eyre::eyre::Report;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
6pub enum ErrorCode {
7 InternalError,
8 IoError,
9 StorageError,
10 SerializationError,
11 CollectionNotFound,
12 CollectionAlreadyExists,
13 UniqueConstraintViolation,
14 ProtocolError,
15 InvalidOperation,
16 InvalidInput,
17 NotFound,
18 InvalidKey,
19 InvalidValue,
20 InvalidDefinition,
21 QueryError,
22 SchemaError,
23}
24
25#[derive(Debug)]
26pub struct AqlError {
27 pub code: ErrorCode,
28 pub message: String,
29 pub source: Option<Report>,
30}
31
32impl AqlError {
33 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
34 Self {
35 code,
36 message: message.into(),
37 source: None,
38 }
39 }
40
41 pub fn from_error<E>(code: ErrorCode, message: impl Into<String>, err: E) -> Self
42 where
43 E: Into<Report>,
44 {
45 Self {
46 code,
47 message: message.into(),
48 source: Some(err.into()),
49 }
50 }
51
52 pub fn invalid_operation(msg: impl Into<String>) -> Self {
54 Self::new(ErrorCode::InvalidOperation, msg)
55 }
56
57 pub fn schema_error(msg: impl Into<String>) -> Self {
58 Self::new(ErrorCode::SchemaError, msg)
59 }
60}
61
62impl fmt::Display for AqlError {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "[{:?}] {}", self.code, self.message)
65 }
66}
67
68impl std::error::Error for AqlError {
69 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
70 self.source
71 .as_ref()
72 .map(|r| r.as_ref() as &(dyn std::error::Error + 'static))
73 }
74}
75
76pub type Result<T> = std::result::Result<T, AqlError>;
78
79impl From<std::io::Error> for AqlError {
80 fn from(err: std::io::Error) -> Self {
81 Self::from_error(ErrorCode::IoError, "IO Error", err)
82 }
83}
84
85impl From<sled::Error> for AqlError {
86 fn from(err: sled::Error) -> Self {
87 Self::from_error(ErrorCode::StorageError, "Storage Error", err)
88 }
89}
90
91impl From<serde_json::Error> for AqlError {
92 fn from(err: serde_json::Error) -> Self {
93 Self::from_error(ErrorCode::SerializationError, "Serialization Error", err)
94 }
95}
96
97impl From<bincode::Error> for AqlError {
98 fn from(err: bincode::Error) -> Self {
99 Self::from_error(ErrorCode::SerializationError, "Bincode Error", err)
100 }
101}
102
103impl From<std::time::SystemTimeError> for AqlError {
104 fn from(err: std::time::SystemTimeError) -> Self {
105 Self::from_error(ErrorCode::InternalError, "System Time Error", err)
106 }
107}
108
109impl From<zip::result::ZipError> for AqlError {
110 fn from(err: zip::result::ZipError) -> Self {
111 Self::from_error(ErrorCode::InternalError, "Zip Error", err)
112 }
113}
114
115impl From<csv::Error> for AqlError {
116 fn from(err: csv::Error) -> Self {
117 Self::from_error(ErrorCode::InternalError, "CSV Error", err)
118 }
119}