1use serde::{Deserialize, Serialize};
2use thiserror::Error;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum DataErrorCode {
14 InvalidDescriptor,
15 InvalidType,
16 UnknownConverter,
17 CycleDetected,
18 UnsupportedFeature,
19 Serialization,
20 Internal,
21}
22
23#[derive(Debug, Clone, Error, Serialize, Deserialize)]
31#[error("{code:?}: {message}")]
32pub struct DataError {
33 code: DataErrorCode,
34 message: String,
35}
36
37impl DataError {
38 pub fn new(code: DataErrorCode, message: impl Into<String>) -> Self {
39 Self {
40 code,
41 message: message.into(),
42 }
43 }
44
45 pub fn code(&self) -> DataErrorCode {
46 self.code
47 }
48
49 pub fn message(&self) -> &str {
50 &self.message
51 }
52}
53
54pub type DataResult<T> = Result<T, DataError>;
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn serde_round_trip() {
63 let err = DataError::new(DataErrorCode::InvalidType, "bad type");
64 let json = serde_json::to_string(&err).expect("serialize");
65 let back: DataError = serde_json::from_str(&json).expect("deserialize");
66 assert_eq!(back.code(), DataErrorCode::InvalidType);
67 assert_eq!(back.message(), "bad type");
68 }
69}