1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use serde::Serialize;
use std::fmt;
use thiserror::Error;

/// An error that occurs while encoding a record.
#[derive(Error, Debug)]
pub enum EncodingError {
    #[error("Serialization failed")]
    SerdeJson(#[from] serde_json::Error),
    #[error("Serialization did not return an object")]
    NotAnObject,
    #[error("Invalid patch")]
    Patch(#[from] json_patch::PatchError),
}

/// An error that occurs while decoding a record.
#[derive(Error, Debug)]
pub enum DecodingError {
    #[error("Deserialization failed")]
    SerdeJson(#[from] serde_json::Error),
    #[error("Type mismatch: expected {0}, got {1}")]
    TypeMismatch(String, String),
    #[error("Deserialization did not return an object")]
    NotAnObject,
}

#[derive(Debug, Serialize)]
pub struct ValidationError {
    message: String,
}

impl<E> From<E> for ValidationError
where
    E: std::error::Error + Send + 'static,
{
    fn from(e: E) -> Self {
        Self::from_error(e)
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl ValidationError {
    pub fn with_message(message: String) -> Self {
        Self { message }
    }
    pub fn from_error<E>(error: E) -> Self
    where
        E: std::error::Error + Send + 'static,
    {
        Self {
            message: format!("{}", error),
        }
    }
}